小编Kha*_*tne的帖子

哪些是访问类中变量的最佳实践?

如果我有一个对象,并且在该对象中我已经定义了一个变量,那么这些方法中哪一个被认为是"最好的"来访问变量?

方法一

使用getter函数

class MyClass:
    def __init__(self):
        self.the_variable = 21 * 2

    def get_the_variable(self):
        return self.the_variable

if __name__ == "__main__"
    a = MyClass()
    print(a.get_the_variable())
Run Code Online (Sandbox Code Playgroud)

方法二

使用@property装饰器

class MyClass:

    def __init__(self):
        self._the_variable = 21 * 2

    @property
    def the_variable(self):
        return self._the_variable

if __name__ == "__main__"
    a = MyClass()
    print(a.the_variable)
Run Code Online (Sandbox Code Playgroud)

方法三

只需直接访问它

class MyClass:
    def __init__(self):
        self.the_variable = 21 * 2

if __name__ == "__main__"
    a = MyClass()
    print(a.the_variable)
Run Code Online (Sandbox Code Playgroud)

这些方法中的任何一种都比其他方法更加pythonic吗?

python python-3.x

6
推荐指数
1
解决办法
103
查看次数

标签 统计

python ×1

python-3.x ×1