[英]Inherit attribute from class that is isn't passed into __init__ method
Ok, so let's say I'm making a class and a child class like this:好的,假设我正在制作一个 class 和一个孩子 class ,如下所示:
class A:
def __init__(self, list1=[], list2=[]):
self.list1 = []
self.list2 = []
class B(A):
def __init__(self, list2=[]):
super().__init__(list2)
But, is there a way to implement it like this但是,有没有办法像这样实现它
class A:
def __init__(self):
self.list1 = []
self.list2 = []
class B(A):
# code here to inherit list1 or list2 from class A
Basically, a way to implement it so the user can't give a value for list1 and list2 (they'd be initialized as empty lists and the user can add elements later with some method) and have class B inherit a list from class A基本上,一种实现它的方法,因此用户不能为 list1 和 list2 提供值(它们将被初始化为空列表,用户可以稍后使用某种方法添加元素)并让 class B 从 class A 继承一个列表
I feel like there is a way to do this other than my workaround, but maybe not because it's a really specific problem我觉得除了我的解决方法之外还有其他方法可以做到这一点,但可能不是因为这是一个非常具体的问题
The code you provided already does what you want it to do.您提供的代码已经完成了您希望它执行的操作。
class A:
def __init__(self):
self.list1 = []
self.list2 = []
class B(A):
pass
b = B()
print(b.list1) # prints []
When you inherit a class, you inherit all of its methods, including __init__
.当你继承 class 时,你继承了它的所有方法,包括
__init__
。 Therefore, A.__init__
is (implicitly) called when initializing B
.因此,在初始化
B
时(隐式)调用A.__init__
。 It's roughly equivalent to大致相当于
class A:
def __init__(self):
self.list1 = []
self.list2 = []
class B(A):
def __init__(self):
super().__init__()
which means (almost) the same thing.这意味着(几乎)相同的事情。 You would never do this just to be more explicit;
你永远不会为了更明确而这样做; you would only do it if you wanted to add behavior to
B.__init__
that A.__init__
shouldn't have.如果您想向
B.__init__
添加A.__init__
不应该有的行为,您只会这样做。
Your code already does what you want:您的代码已经完成了您想要的操作:
class A:
def __init__(self):
self.list1 = []
self.list2 = []
class B(A):
# code here to inherit list1 or list2 from class A
def __init__(self):
super().__init__() # <- This calls class A init function which creates the two empty lists
Your code does nothing with the user-provided lists.您的代码对用户提供的列表没有任何作用。 I think you meant this:
我想你的意思是:
class A:
def __init__(self, list1=[], list2=[]):
self.list1 = list1
self.list2 = list2
class B(A):
def __init__(self, list2=[]):
super().__init__(list2=list2)
And if you want to inherit the lists in class B from class A, your code has to be as follows:如果你想从 class A 继承 class B 中的列表,你的代码必须如下:
class A:
def __init__(self):
self.list1 = []
self.list2 = []
class B(A):
pass
And for modification of the lists, provide a setter function:对于列表的修改,提供一个设置器function:
class A:
def __init__(self):
self.list1 = []
self.list2 = []
def set_list1(list):
self.list1 = list
def set_list2(list):
self.list2 = list
class B(A):
pass
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.