python 元类创建行为 子类会继承么
发布网友
发布时间:2022-04-30 12:47
我来回答
共2个回答
热心网友
时间:2022-04-18 05:27
# 自定义一个元类继承type
class MyType(type):
def __new__(cls, class_name, class_bases, class_attrs):
# 创建一个新的字典,将就旧字典(class_attrs)中的所有key变为大写
new_attrs = {}
for key,value in class_attrs.items():
if not key.startswith('__'):
new_attrs[key.upper()] = value
#条用type元类的__new__方法生成一个类对象,此类对象的所有属性都变为大写
return type.__new__(cls, class_name, class_bases, new_attrs)
# 定义A类 元类使用MyType
class A(object, metaclass=MyType):
a = 5
# 定义B类,并继承自A类
class B(A):
b = 6
if __name__ == '__main__':
print(hasattr(A, 'a')) False
print(hasattr(A, 'A')) True
print(hasattr(B, 'b')) False
print(hasattr(B, 'B')) True
A类和其子类B类中的属性都变成了大写,所以metaclass是可以被继承的
热心网友
时间:2022-04-18 06:45
<pre>#!/usr/bin/pythonclass Ppoint: def __init__(self, x, y): self.x = x self.y = y # def __del__(self): # class_name = self.__class__.__name__ # print class_name, "destroyed"class Spring_Point(Ppoint): def __init__(self): Ppoint.__init__(self, 1, 2) # super(Spring_Point, self).__init__(1, 2)if __name__ == "__main__": xx = Spring_Point() print xx.__dict__</pre>
以上是用old的方式来创建一个class, Ppoint, class Spring_Point继承Spring_Point, 在调用父类的构造函数的时候,必须使用
<pre>Ppoint.__init__(self, 1, 2)</pre>
不能使用
<pre>super(Spring_Point, self).__init__(1, 2)</pre>
如果使用心得方式创建类
<pre>#!/usr/bin/pythonclass Ppoint(object): def __init__(self, x, y): self.x = x self.y = y # def __del__(self): # class_name = self.__class__.__name__ # print class_name, "destroyed"class Spring_Point(Ppoint): def __init__(self): Ppoint.__init__(self, 1, 2) # super(Spring_Point, self).__init__(1, 2)if __name__ == "__main__": xx = Spring_Point() print xx.__dict__</pre>