我对Python相对较新,并且对不可变变量有疑问。
我正在尝试更改类属性的值(例如car.color)。困难在于,我无法使用car的命名空间来执行此操作。
到目前为止,我还没有找到令人满意的答案。在下面的代码中,我试图总结发现的可能解决方案(工作环境)及其缺点:
class Car:
def __init__(self):
self.color = "green"
self.color_list = ["green"]
self.color_attrib = "green"
self.name = "VW Golf"
"""
and many more attributes...
"""
def makesetter(self, attribute):
def set_value(value):
attribute=value
return set_value
def set_color(self, value):
"in this function I directly have access to car.color and can change its value: "
self.color = value
def set_attrib(self, attribute_string, value):
setattr(self,attribute_string,value)
def change_attribute(attribute, value):
"In this function I can not access car.color directly"
attribute=value
def change_attribute_list(attribute, value):
"In this function I …Run Code Online (Sandbox Code Playgroud)