Python,自动将属性添加到子类

时间:2018-03-11 15:24:37

标签: python inheritance

我想自动将一个属性添加到从A类继承的某些对象中。 这些对象只能从包含我要复制的属性的另一个对象实例化:

class A(object):
    pass

class B(A):
    pass

class C(object):
    pass

class MyClass(MySuperClass):
    def __init__(self):
        MySuperClass.__init__(self)

        b = B()
        hasattr(b, "my_attribut")  # True

        c = C()
        hasattr(c, "my_attribut")  # False, doesn't inherit from A


b = B() # Raise error, this object can't be instantiated here.

也许使用MetaClass?

1 个答案:

答案 0 :(得分:0)

类属性

如果要添加属性,那么确实可以使用仅影响子类行为的元类。

class MetaA(type):
    def __new__(cls, name, bases, name_space):
        # Metaclass does nothing for A
        if not bases:
            return type.__new__(cls, name, bases, name_space)

        # Metaclass adds a class attribute to anything that inherits A
        else:
            return super().__new__(cls, name, bases, dict(name_space, my_attribute='foo'))

class A(metaclass=MetaA):
    pass

class B(A):
    pass

hasattr(A, "my_attribute") # False
hasattr(B, "my_attribute") # True

实例属性

如果你想要的是你的对象有一个实例属性,如果它们的类继承自A,那么元类就不会这样做。您可以在A.__init__

中添加条件语句
class A:
    def __init__(self):
        if type(self) != A:
            self.my_attribute = 'foo'

class B(A):
    pass

hasattr(A(), "my_attribute") # False
hasattr(B(), "my_attribute") # True