python - 如何访问不同类的对象?

标签 python python-2.7 python-3.x class oop

共有三个类:

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/

相关文章:

python - 从数据框列的列表中查找字符串值并将字符串值附加为列

python - 根据现有词典制作词典列表

python - 无法在 OS X 上安装 MySQL-python

python - 使用 Altair 直接标记线图

Python 脚本不更新变量

Python如何在数据框中应用.replace以更改大量值

python - 如何将列表从 View 传递到 django 中的模板

python - 在python中对并行列表进行排序 - 第一项降序,第二项升序

python - Vim 中的 Google Pytype

python - 使用 Python 3.x 启动 Firefox