如何从不同的类访问对象?

时间:2017-09-21 07:48:30

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

有三个类:

A,B和C

B的__init__创建A的对象。使用mutators,我将能够为创建的实例更改A的属性。

但是,我无法找到任何方法来使用B创建的A实例在C中使用而不将Object明确传递给__init__方法[ < em> 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

3 个答案:

答案 0 :(得分:2)

这是一个简单的例子:

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

答案 1 :(得分:1)

假设我们有A和B类:

class A:
    def hello_world(self):
        print("hello world")

class B:
    def __init__(self):
        self.a = A()
    def hello_world(self):
        self.a.hello_world()

您创建了一个B类实例(它将在其中创建一个A类实例):

b = B()

然后,您可以将对bb.a的引用传递给C类实例的任何函数(无论是否为构造函数)

class C:
    def hello_world(self, a):
        a.hello_world()

c = C()
c.hello_world(b.a)

您还可以使用全局变量:

class C:
    def hello_world(self):
        b.a.hello_world()

c = C()
c.hello_world()

这里C类的实例将依赖于变量b,并且只使用其a属性。

通常认为在类中使用全局变量很难维护并且是不好的做法。如果你的类依赖于某个类的值或实例,你应该在构造函数(__init__函数)或使用它的函数中传递引用。

答案 2 :(得分:0)

如果这些类在不同的python文件中,那么您也可以通过导入类名并创建该类的对象来使用这些类: 例如:

file1.py

class A:
    def __init__(self):
        x = []
        y = []

file2.py

from file1 import A
class C :
    def __init__(self):
    [get obj1 without passing the instance in init]
    self.value = None
    self.obj_a = A()

    def xyz(self):
      print "in class c"

file3.py

from file2 import C
from file1 import A
Class B:
    def __init__(self):
       self.obj_a = A()
       self.obj_c = C()

    def another_func(self):
       print self.obj_c.xyz()# it will print "in class c"
相关问题