目录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 装饰器装饰的方法就是非绑定方法, 就是一个普通的函数