目錄python
繼承父類,則會有父類的全部屬性和方法函數
class ParentClass1(): pass class ParentClass2(): pass class SubClass(ParentClass1,ParentClass2): pass
繼承父類的同時本身有init,而後也須要父類的initcode
class ParentClass1(): def __init__(self,name): pass class SubClass(ParentClass): def __init__(self,age): # 1. ParentClass1.__init__(self,name) # 2. super(SubClass,self).__init__(name) self.age = age
類對象能夠引用/當作參數傳入/當作返回值/當作容器元素,相似於函數對象對象
class ParentClass1(): count = 0 def __init__(self,name): pass class SubClass(ParentClass): def __init__(self,age): self.age = age pc = ParentClass1() sc = SubClass() sc.parent_class = pc # 組合 sc.parent_class.count # 0
新式類:繼承object的類,python3中全是新式類繼承
經典類:沒有繼承object的類,只有python2中有get
在菱形繼承的時候,新式類是廣度優先(老祖宗最後找);經典類深度優先(一路找到底,再找旁邊的)it
一種事物的多種形態,動物-->人/豬/狗class
# 多態 import abc class Animal(metaclass=abc.ABCmeta): @abc.abstractmethod def eat(): print('eat') class People(Animal): def eat(): pass class Pig(Animal): def eat(): pass def run(): pass class Dog(Animal): # 報錯 def run(): pass # 多態性 peo = People() peo.eat() peo1 = People() peo1.eat() pig = Pig() pig.eat() def func(obj): obj.eat() class Cat(Animal): def eat(): pass cat = Cat() func(cat)
鴨子類型:只要長得像鴨子,叫的像鴨子,游泳像鴨子,就是鴨子.import
隱藏屬性,只有類內部能夠訪問,類外部不能夠訪問容器
class Foo(): __count = 0 def get_count(self): return self.__count f = Foo() f.__count # 報錯 f._Foo__count # 不能這樣作
把方法變成屬性引用
class People(): def __init__(self,height,weight): self.height = height self.weight = weight @property def bmi(self): return weight/(height**2) @bmi.setter def bmi(self,value) print('setter') @bmi.deleter def bmi(self): print('delter') peo = People peo.bmi
沒有任何裝飾器裝飾的方法就是對象的綁定方法, 類能調用, 可是必須得傳參給self
被 @classmethod 裝飾器裝飾的方法是類的綁定方法,參數寫成cls, cls是類自己, 對象也能調用, 參數cls仍是類自己
被 @staticmethod 裝飾器裝飾的方法就是非綁定方法, 就是一個普通的函數