欢迎光临散文网 会员登陆 & 注册

python 6 面向对象

2023-03-04 10:34 作者:戎码关山  | 我要投稿

面向对象比面向过程的编程更加具有健壮性,能够在对程序细节进行调整而不影响整体性能

#类的定义
class Triangle:
    def __init__(self,x,y,z):
        self.a = x
        self.b = y
        self.c = z
    
    def perimeter(self):
        return self.a+self.b+self.c

t1 = Triangle(3,4,5)
t2 = Triangle(6,8,10)
print(t1.perimeter())
print(t2.perimeter())

#类的属性
class Human:
    '''这里是对于Human类的解释'''
    name = 'human'  #类属性,公有属性
    __id = 0    #私有属性
    def __str__(self):
        return '对内置str函数的测试,将打印对象的相关信息'

print(Human.name)
#print(Human.__id)#AttributeError: type object 'Human' has no attribute '__id'

#类的内置属性
h = Human()
print(Human.__doc__)#打印注释
print(h)#重写__str__函数

#类的继承
class A:
    def __init__(self):
        self.id = 1
    def a(self):
        print('class A')

class B(A):
    pass
b = B()
print(b.id)
b.a()

#重载
#方法重载
class C(A):
    def __init__(self):
        self.id = 2
    def a(self):
        print('in class C')
c = C()
c.a()
#运算符重载
class Mylist:
    def __init__(self,*args):
        self.__mylist = []
        for arg in args:
            self.__mylist.append(arg)
    def __add__(self,x):
        for i in range(len(self.__mylist)):
            self.__mylist[i] = self.__mylist[i] + x
    def show(self):
        print(self.__mylist)
l = Mylist(1,2,3,4,5)
l.show()
l + 5
l.show()
# 还可以重载__sub__ , __mul__ , __div__

#多态
#同一个名字的方法在不同类中有不同的作用,这就称作多态
class Shape:
    def perimeter(self):
        raise AttributeError("子类不重载就会爆出异常")
class Triangle(Shape):
    def __init__(self,x,y,z):
        self.a = x
        self.b = y
        self.c = z
    
    def perimeter(self):
        print(self.a+self.b+self.c)
class Square(Shape):
    def __init__(self,x):
        self.a = x
        
    
    def perimeter(self):
        print(self.a * 4)
t = Triangle(1,1,1)
s = Square(2)
t.perimeter()
s.perimeter()

#内置装饰器
#staticmethod,classmethod,property
class D:
    @staticmethod
    def sm():
        print('静态方法')
    
    @classmethod
    def cm(self):
        print('类方法')
    
d = D()
d.sm() 
D.sm()
d.cm()
D.cm()

class Triangle:
    def __init__(self,x,y,z):
        self.a = x
        self.b = y
        self.c = z
    @property  #只读属性
    def perimeter(self):
        print(self.a+self.b+self.c)
t = Triangle(1,1,1)
t.perimeter
#加了@property后,可以用调用属性的形式来调用方法,后面不能加()


python 6 面向对象的评论 (共 条)

分享到微博请遵守国家法律