1、多继承
原则:
1、从左到右继承时,左优先;
2、就近继承;
3、就近继承优先于左继承;
markdown字体颜色设置参考:链接
代码:
class P1:
def foo(self):
print ('p1-foo')
class P2:
def foo(self):
print ('p2-foo')
def bar(self):
print ('p2-bar')
class C1 (P1,P2):
pass
class C2(P1,P2):
def bar(self):
print ('C2-bar')
class D(C1,C2):
pass
d = D()
d.foo()
d.bar()
输出:
p1-foo
C2-bar
参考:链接
2、raise NotImplementedError
在子类继承父类中,raise NotImplementedError 通常用于父类函数,如果子类生成的对象调用父类函数时没有完成重写,则会报这个raise NotImplementedError 错误。
参考:链接
3、python私有变量
定义对象的私有变量,格式为:对象.__变量名,注意是2个下划线,
代码:
class Teacher():
__item = 111
def __init__(self,name,level):
self.__name=name
self.__level=level
#获取老师的等级
def get_level(self):
return self.__level
#获取名字
def get_name(self):
return self.__name
t=Teacher("GG",5)
print("level is: ",t.get_level()) #可行
print("name is",t.get_name())
print(t._Teacher__name)
输出:
level is: 5
name is GG
GG
如果打印print(t.name),会输出如下错误,也就是说对象没有name这个属性,
参考:链接1
4、__all__用法
参考:链接1
5、类变量、类方法、实例变量、实例方法
类变量:在类中,实例方法外赋值,用类名调用,也可以用对象调用
类方法:使用@classmethod,用类名调用,也可以用对象调用
实例变量:用对象调用
实例方法:用对象调用,也可以用类名调用,但需要使用对象变量,即:类名.实例方法(对象)格式进行调用
6、装饰器
参考:
1、python中的装饰器(基础装饰器),
2、Python之闭包,
3、Python之变量作用域,