面试题答案
一键面试-
定义元类:
class MetaClass(type): def __new__(cls, name, bases, attrs): new_attrs = attrs.copy() # 为子类添加特定方法 def new_method(self): return "这是自动添加的方法" new_attrs['new_method'] = new_method # 为子类添加特定属性 new_attrs['new_attribute'] = '这是自动添加的属性' return super().__new__(cls, name, bases, new_attrs)
-
使用元类定义父类:
class Parent(metaclass = MetaClass): pass
-
定义子类:
class Child(Parent): pass
-
类继承机制和元类机制协同工作解释:
- 类继承机制:子类(如
Child
)从父类(如Parent
)继承属性和方法。当创建Child
实例时,它可以访问父类的属性和方法,如果父类中没有相应的属性或方法,会按照MRO
(方法解析顺序)继续向上查找。 - 元类机制:元类(如
MetaClass
)负责创建类。在创建类(如Parent
和Child
)时,__new__
方法被调用。__new__
方法接收类的名称、基类元组和属性字典作为参数。在__new__
方法中,我们可以动态修改属性字典,为类添加新的方法或属性,然后通过super().__new__
创建并返回新的类对象。这样,在子类继承父类的过程中,由于父类是由元类创建,子类也会继承元类为父类添加的方法和属性。
- 类继承机制:子类(如
-
验证:
child = Child() print(child.new_method()) print(child.new_attribute)
输出结果:
这是自动添加的方法 这是自动添加的属性