首页 > 解决方案 > 如何在 Python 中将列表从一个类调用到另一个类?

问题描述

class A:
     myList = ['0', '2', '3']
     def hello (self):
          print("Hello!")

class B:

如何将 A 类中的 myList 放入 B 类?

我试图在 B 类中简单地执行“print(myList)”,但没有成功。有没有办法做到这一点?

提前致谢。

标签: python

解决方案


myList成员属于A,因此,如果要访问它,则需要使用A.myList.

但是,这在面向对象的代码中通常是一个坏主意,因为这意味着该成员不受类的控制(即,未封装):

class A:
    myList = [0, 2, 3]                  # Normal variable, public.
    def doSomething(self):
        print('A', A.myList)

class B:
    def doSomethingBad(self):
        print('B', A.myList)            # Print and modify original.
        A.myList = [42]

a = A()
b = B()
a.doSomething()
b.doSomethingBad()
a.doSomething()                         # Shows changed value.

其输出表明封装已被绕过:

('A', [0, 2, 3])
('B', [0, 2, 3])
('A', [42])

理想情况下,您需要一个可以返回成员副本的成员函数,这样您就可以对它做任何您想做的事情,而不会破坏封装,例如:

class A:
    __myList = [0, 2, 3]                # Dunder variable, private.
    def doSomething(self):
        print('A', A.__myList)

    @classmethod                        # Class method to return copy.
    def getCopy(self):
        return [x for x in A.__myList]

class B:
    def doSomethingGood(self):
        myList = A.getCopy()            # Get copy for print and change.
        print('B', myList)
        myList = [42]

a = A()
b = B()
a.doSomething()
b.doSomethingGood()
a.doSomething()                         # Still shows original.

使用该方法,强制执行封装:

('A', [0, 2, 3])
('B', [0, 2, 3])
('A', [0, 2, 3])

如果您确实尝试A使用print('B', A.__myList)within访问/更改的原始副本B,您会看到它是被禁止的:

Traceback (most recent call last):
  File "/home/pax/testprog.py", line 13, in doSomething
    print('B', A.__myList)
AttributeError: class A has no attribute '_B__myList'

推荐阅读