class A:
myList = ['0', '2', '3']
def hello (self):
print("Hello!")
class B:
如何将A类中的myList放入B类中?
我试图在B类中简单地执行“ print(myList)”,但是没有运气。甚至有办法吗?
谢谢。
答案 0 :(得分:1)
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)
来访问/更改B
的原始副本,您会发现它被禁止:< / p>
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'