什么是元类?
元类就是用来创建类的“东西”
Python中类也是一种对象。
#定义一个类
# Python解释器在执行的时候会创建一个对象
class Test:
pass
print(type(Test))
# 使用type方法查看类类型<class 'type'>
# type拥有创建类的功能
type可以动态的创建类。
type(类名, 由父类名称组成的元组,包含属性的字典)
#创建一个Person类,属性:年龄 18
Person = type("Person", (), {"age": 18})
print(Person)
print(Person.__class__)
p1 = Person()#创建Person的实例对象
print(p1.__class__)
#Student继承Person
Student = type("Student", (Person,), {"gender": False})
print(Student)
print(Student.__bases__)
print(Student.age)
#创建Student的实例对象
s = Student()
#类名直接访问属性
print(Student.gender)
#实例对象访问属性
print(s.gender)
添加实例方法、静态方法、类方法
def eat(self):
print("eatting...")
@staticmethod
def run():
print("running...")
@classmethod
def sleep(cls):
print("sleeping...")
#传的是方法名,即引用
Student = type("Student",(Person,),{"gender": False,"eat":eat,"run":run,"sleep":sleep})
#创建实例对象,访问方法属性
s2 = Student()
s2.eat()
s2.run()
s2.sleep()
print(s2.gender)
#类名直接访问方法属性
# Student.eat()类不可以调用实例属性和方法
Student.run()
Student.sleep()
print(Student.gender)
自定义元类
元类的调用
Python在创建Student类时先不在内存中创建、首先查看Student中有
metaclass__这个属性吗
如果有,Python会通过__metaclass__创建一个名字为Student的类(对象)
如果Python没有找到__metaclass,它会继续在Person(父类)中寻找
__metaclass__属性,并尝试做和前面同样的操作。如果还是找不到
metaclass,Python就会用内置的type来创建这个类对象
# 例子:实现所有的属性均需要以类名开始
def renameattribute(classname, parentclass, attributedic):
newattribute = {}
for key, value in attributedic.items():
if not key.startswith("__"):
key = classname.lower() + key
newattribute[key] = value
# for key, value in newattribute.items():
# print(key, value)
return type(classname, parentclass, newattribute)
class AI(object, metaclass=renameattribute):
isalive = False
ai = AI()
print(hasattr(ai,"isalive")) #false
print(hasattr(ai,"aiisalive")) #true