繁体   English   中英

如何在另一个 class 中使用 class 中的变量

[英]How to use a variable from a class in another class

因此,对于这种情况,我在名为 A 的 class 中有一个字符串列表。在这个 class 中,它更新列表中的任何元素。 例如:

class A:
    def __init__(self, size):
        self.size = size
        self._list = ['BBB']

    def change(self):
        self._grid[0][2] = '*'

然后,我需要使用一个名为 B 的 class 打印出这样的字符串:

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

只需访问 A 变量的属性。

class B:
    
    def foo(self):
        a = A(10)
        a.change()
        print(a._list[0])

但是,Python 约定是使用前导下划线作为提示,表明该属性仅供 class 内部使用。如果需要,class 通常应提供一种检索值的方法; 这可以使用@property装饰器来完成(通常_list属性对应于list属性)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM