共有三个类:
A、B 和 C
__init__
B 的创建 A 的对象。使用更改器(mutator),我将能够为创建的实例更改 B 的 A 属性。
但是,我无法找到任何方法来使用 B 创建的 A 实例在 C 中使用,而无需将对象显式传递给 __init__
方法 [ not C.__init(self, object: A) ]
有没有办法隐式允许 C 使用 A 的实例?
我是 python 新手,不确定这是否是一个有效的问题。我查看了其他来源,其中它将对象显式传递给类 C
class A:
def __init__(self):
x = []
y = []
class C :
def __init__(self):
#[get obj1 without passing the instance in init]
self.value = None
def method1():
self.value = len([]) #len(obj1 of A.x)
class B:
def __init__(self):
obj1 = A()
obj1.x = [1,2,3,4]
obj1.y = [1,2,3]
obj2 = B()
print(obj2.value) #this should be the length of x in the instance A created above
最佳答案
这是一个简单的例子:
class A:
def __init__(self, i = ""):
self.item = i
class B:
def __init__(self):
self.a = A("hello")
class C:
def __init__(self):
b = B()
print(b.a.item)
c = C()
输出:
hello
关于python - 如何访问不同类的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46338275/