[英]How to pass an instance of a class into attributes within its constructor and have those attributes access initialized attributes?
say I have 3 classes in python foo,bar and baz as follows:假设我在 python foo、bar 和 baz 中有 3 个类,如下所示:
class Foo(object):
a=9
def __init__(self):
self.bar= Bar(Foo)
self.baz = Baz(Foo)
class Bar(object):
def __init__(self,Foo):
self.a = Foo.a
def f(self,b):
return self.a*b
class Baz(object):
def __init__(self,Foo):
self.b = Foo.bar.f(8)
print(self.b)
k=Foo()
Doing it as such raises the error:这样做会引发错误:
AttributeError: type object 'foo' has no attribute 'bar' AttributeError:类型 object 'foo' 没有属性 'bar'
unsure how to proceed as I would like to pass in that class's instance of itself into the constructors of other classes and have those instance attributes accessible by others within the constructor.不确定如何继续,因为我想将该类的实例传递给其他类的构造函数,并让构造函数中的其他人可以访问这些实例属性。 I have looked around but unfortunately have not found something similar in nature within the scope of python我环顾四周,但不幸的是在 python 的 scope 中没有发现类似的东西
You want to pass self
(the instance of Foo
being initialized) to Bar
and Baz
, not the class Foo
itself.您想将self
(正在初始化的Foo
的实例)传递给Bar
和Baz
,而不是 class Foo
本身。
class Foo(object):
a=9
def __init__(self):
self.bar = Bar(self)
self.baz = Baz(self)
If this is correct, then running your code should produce the output 72
.如果这是正确的,那么运行您的代码应该会生成 output 72
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.