[英]Python Dynamic Inheritance and Attributes
我正在寻找一种解决方案,允许我根据满足的某些条件(Python 3.6)动态继承类。 看起来很简单,但我无法在子类中获得父类的属性。 一切依赖于self
要么产生一个缺少参数的错误,要么属性不出现。 我为动态继承实现了here和here给出的问题的解决方案,但仍然遇到与子类属性相同的问题。
对于样品:
class Parent:
def __init__(self):
self.some_value = 1
def some_function(self):
return self.some_value
def classFactory(parent):
class child(parent):
def __init__(self, parent):
super(child, self).__init__()
parent.__init__(self)
self.some_other_value = 2
def some_other_function(self):
return self.some_value + self.some_other_value
return child
child_class = classFactory(Parent)
child_class.some_value
AttributeError: type object 'child' has no attribute 'some_value'
child_class.some_other_value
AttributeError: type object 'child' has no attribute 'some_other_value'
child_class.some_other_function()
TypeError: some_other_function() missing 1 required positional argument: 'self'
但是,如果我采用相同的child
构造并将其从函数定义中删除,它就可以工作。
class child(Parent):
def __init__(self, parent):
super(child, self).__init__()
parent.__init__(self)
self.some_other_value = 2
def some_other_function(self):
return self.some_value + self.some_other_value
child_class = child(Parent)
print(child_class.some_value)
# 1
print(child_class.some_other_value)
# 2
print(child_class.some_other_function())
# 3
为什么属性在第一种情况下没有被继承,而在第二种情况下被继承? 我如何编写动态继承来给我我期望的行为(如第二种情况所示)?
如果我在return child(parent)
使用 parent 参数实例化子类,它会起作用。 这保留了父级和子级的属性和方法。
class Parent:
def __init__(self):
self.some_value = 1
def some_function(self):
return self.some_value
def classFactory(parent):
class child(parent):
def __init__(self, parent):
parent.__init__(self)
self.some_other_value = 2
def some_other_function(self):
return self.some_value + self.some_other_value
return child(parent)
child_class = classFactory(Parent)
print(child_class.some_value)
# 1
print(child_class.some_other_value)
# 2
print(child_class.some_other_function())
# 3
print(child_class.some_function())
# 1
最显式的动态继承实现可以用元类实现:
class A:pass
class B:pass
class Meta(type):
def __new__(cls, name, bases, dct):
bases = (A,) if Meta.condition() else (B,)
return type(name, bases, dct)
@staticmethod
def condition():
# implement condition.
...
class C(metaclass=Meta):
pass
c_instance = C()
print("is C instance of A:")
print(isinstance(c_instance, A))
print("is C instance of B:")
print(isinstance(c_instance, B))
或者,您可以定义条件函数,如下所示:
condition = lambda: True
class D(A if condition() else B):
pass
d_instance = D()
print("is D instance of A:")
print(isinstance(d_instance, A))
print("is C instance of B:")
print(isinstance(d_instance, B))
使用元类的方法将使您更好地控制类的创建,因此这取决于您的需求......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.