基础部分python学完,咱们可以深入了解下python高阶知识点,让我们一起来学习吧!
1.面向对象进阶
1)元类
1.1.1:type创建class类
python创建类:
class ObjectCreator:
pass
写了classpython编译器就自动创建了class类了,内部创建的原理是通过type元组来创建:type(类名, 由父类名称组成的元组(针对继承的情况,可以为空),包含属性的字典(名称和值))如:Test2 = type("Test2",(),{}) #定了一个Test2类;
元类就是用来创建这些类(对象)的,元类就是类的类,你可以这样理解为
MyClass = MetaClass() #使用元类创建出一个对象,这个对象称为“类”
MyObject = MyClass() #使用“类”来创建出实例对象
1.1.2:python对象属性__metaclass__的有趣地方
__metaclass__属性:创建类时会先在里面查找是否有__metaclass__属性,有的话就通过这个属性指定的方法创建类;没有就往上级找指到找到,没有找到就通过type方式创建
class Foo(object): __metaclass__ = something… ...省略...
例子:通过__metaclass__属性来控制模块里所有的类的属性都应该是大写形式:
#-*- coding:utf-8 -*- def upper_attr(future_class_name, future_class_parents, future_class_attr): #遍历属性字典,把不是__开头的属性名字变为大写 newAttr = {} for name,value in future_class_attr.items(): if not name.startswith("__"): newAttr[name.upper()] = value #调用type来创建一个类 return type(future_class_name, future_class_parents, newAttr) class Foo(object, metaclass=upper_attr): bar = 'bip' print(hasattr(Foo, 'bar')) print(hasattr(Foo, 'BAR')) f = Foo() print(f.BAR)