python 6 面向?qū)ο?/h1>
2023-03-04 10:34 作者:戎碼關(guān)山 | 我要投稿
面向?qū)ο蟊让嫦蜻^程的編程更加具有健壯性,能夠在對程序細節(jié)進行調(diào)整而不影響整體性能
#類的定義
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 '對內(nèi)置str函數(shù)的測試,將打印對象的相關(guān)信息'
print(Human.name)
#print(Human.__id)#AttributeError: type object 'Human' has no attribute '__id'
#類的內(nèi)置屬性
h = Human()
print(Human.__doc__)#打印注釋
print(h)#重寫__str__函數(shù)
#類的繼承
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__
#多態(tài)
#同一個名字的方法在不同類中有不同的作用,這就稱作多態(tài)
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()
#內(nèi)置裝飾器
#staticmethod,classmethod,property
class D:
? ?@staticmethod
? ?def sm():
? ? ? ?print('靜態(tài)方法')
? ?
? ?@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后,可以用調(diào)用屬性的形式來調(diào)用方法,后面不能加()
標(biāo)簽: