Python - 访问父成员
当我试图弄清楚当成员类是外部模块的一部分时如何让成员类从其父级访问数据时,我面临着停滞。
基本上,这是可行的(B类可以访问父类的方法,如下所示: A.say_hi(A) ):
class A:
def __init__(self):
print("Initializing parent object...")
self.child = self.B()
class B:
def __init__(self):
print("Initializing child...")
A.say_hi(A)
def say_hi(self):
print("A class says hi")
但是,如果类开始变得特别大,这可能会变得非常混乱,所以我一直将其他类放在文件中并导入他们内联。问题是,如果我在定义类 B 时尝试使用“import B.py”,我将无法再让成员类访问其父级的成员和函数。
有没有办法获得原始行为而不将成员类保留在与父级相同的文件中?
I'm facing a standstill here while trying to figure out how to have member classes access data from their parent when they are part of an external module.
Basically, this works (the B class can access is parent's methods like so: A.say_hi(A) ):
class A:
def __init__(self):
print("Initializing parent object...")
self.child = self.B()
class B:
def __init__(self):
print("Initializing child...")
A.say_hi(A)
def say_hi(self):
print("A class says hi")
However, this can get pretty messy if classes start getting extra large, so I have been placing my additional classes in files and importing them inline. The problem with that is I can no longer get the member class to access its parent's members and functions if I try to use 'import B.py' when class B is defined within.
Is there any way to get the original behavior without leaving the member class inside the same file as the parent?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
实际上,在您的示例中,您无法访问 B 类中的 A 实例。代码
A.say_hi(A)
确实有效,但错误。这已经在对你的问题的评论中说过了。如果您希望能够访问父实例,则可以执行以下操作:
模块
b
:模块
a
:Actually in your example you couldn't access instance of A in your class B. And the code
A.say_hi(A)
does work however is wrong. This has been said in comments to your question.Here is how you do that if you want to be able to access parent instance:
Module
b
:Module
a
:如果将对象(a)传递给类(b),则可以直接调用它。
If you pass the object (a) to the class (b), you can call it directly.