Python 如何在另一个类中使用一个类中的变量
对于这个例子,我在一个名为a的类中有一个字符串列表。在这个类中,它更新列表中的任何元素。例如:Python 如何在另一个类中使用一个类中的变量,python,Python,对于这个例子,我在一个名为a的类中有一个字符串列表。在这个类中,它更新列表中的任何元素。例如: class A: def __init__(self, size): self.size = size self._list = ['BBB'] def change(self): self._grid[0][2] = '*' 然后,我需要使用一个名为B的类来打印字符串: class B: def print(self):
class A:
def __init__(self, size):
self.size = size
self._list = ['BBB']
def change(self):
self._grid[0][2] = '*'
然后,我需要使用一个名为B的类来打印字符串:
class B:
def print(self):
pass
# with this function, I need to print 'BBB'
# from the list in class A. I can hardcode it,
# but if and when 'BBB' gets updated, so does the
# 'BBB' within this class.
从t只需访问变量的属性即可
class B:
def foo(self):
a = A(10)
a.change()
print(a._list[0])
但是,Python的惯例是使用前导下划线作为提示,表示该属性仅用于类的内部使用。如果需要,类通常应该提供一个方法来检索值;这可以使用
@property
装饰器来完成(通常\u list
属性对应于list
属性)。您能给出一个完整的示例来说明您试图实现的目标吗?B班看起来像什么?你想用它做什么?另外,您的缩进似乎不正确,因为我假设change
应该是类a
上的一个方法。您可以使用variable.\u list
其中variable
包含a
对象。什么是self.\u grid
?这应该是self.\u list
?字符串是不可变的,不能分配给字符串的索引。如果可以,分配给[2]
将创建BB*
,而不是B*B
。您可以使用返回函数将变量从B返回到a中的新变量。