Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 创建类的静态字段的getter/setter以便类的实例可以调用它的最佳方法是什么_Python_Static Methods_Getter Setter - Fatal编程技术网

Python 创建类的静态字段的getter/setter以便类的实例可以调用它的最佳方法是什么

Python 创建类的静态字段的getter/setter以便类的实例可以调用它的最佳方法是什么,python,static-methods,getter-setter,Python,Static Methods,Getter Setter,我想问,这是否是为类静态字段编写get/set函数的最佳方法,该字段是类实例的属性,而不是类本身 class MyClass: __static_field = "something" def __init__(self): pass @staticmethod def get_static_field(): return MyClass.__static_field def get_static_field_wit

我想问,这是否是为类静态字段编写get/set函数的最佳方法,该字段是类实例的属性,而不是类本身

class MyClass:

    __static_field = "something"

    def __init__(self):
        pass

    @staticmethod
    def get_static_field():
        return MyClass.__static_field

    def get_static_field_with_instance(self):
        return self.__class__.__static_field

    def set_static_field_with_instance(self, new_value):
        self.__class__.__static_field = new_value
以下是一些输出:

print(MyClass.get_static_field())
>>> something
obj = MyClass()
print(obj.get_static_field_with_instance())
>>> something
obj.set_static_field_with_instance("smething new")
print(obj.get_static_field_with_instance())
>>> something new

为什么要在python中使用getter和setter?您只需使用
MyClass.\uu static\u field
MyClass.\uu static\u field='新值'
,即可获取或设置值。或者,如果您正在更改实例属性,请使用
obj.\uu static\u field
@Liliane,因为我想封装我的数据,我不知道python中是否需要封装,因为python没有私有变量或私有方法,即..@Liliane-是,但是如果我有表示坐标的字段x和y,该怎么办。如果我从现在开始决定它们不是x和y,而是coords[0]和coords[1]。所有使用我的api的人都必须将代码从.x重写为.coords[1]。使用getter和setter,我将不会有这样的问题,我没有想到这一点。但是,请务必期望您的用户不会以您预期的方式使用API。他们可能会以意想不到的方式使用它。例如,如果您给一个用户getter和setter,他们可能会忽略您使用它的建议,他们会直接使用class属性。这样,如果您将x更改为coords[0],那么您将无意中破坏用户的代码。