Python:访问另一个类的属性和方法 [英] Python: accessing attributes and methods of one class in another
本文介绍了Python:访问另一个类的属性和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有两个班级A和B:
Let's say I have two classes A and B:
Class A:
# A's attributes and methods here
Class B:
# B's attributes and methods here
现在我可以按以下方式评估B类对象中A的属性:
Now I can assess A's properties in object of B class as follows:
a_obj = A()
b_obj = B(a_obj)
我需要的是双向访问. 如何访问B中的A属性和A中的B属性?
What I need is a two way access. How do I access A's properties in B and B's properties in A ?
推荐答案
您需要使用以下两种方式创建指针:
You need to create pointers either way:
class A(object):
parent = None
class B(object):
def __init__(self, child):
self.child = child
child.parent = self
现在A
可以引用self.parent
(前提是它不是None
),而B
可以引用self.child
.如果您尝试将A
的实例作为多个B
的子代,则最后一个父代"获胜.
Now A
can refer to self.parent
(provided it is not None
), and B
can refer to self.child
. If you try to make an instance of A
the child of more than one B
, the last 'parent' wins.
这篇关于Python:访问另一个类的属性和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文