是否有python函数来重命名对象';s属性?
基本上,是否已经有一个内置的或常用的功能来实现这一点:是否有python函数来重命名对象';s属性?,python,Python,基本上,是否已经有一个内置的或常用的功能来实现这一点: def rename_attribute(object_, old_attribute_name, new_attribute_name): setattr(object_, new_attribute_name, getattr(object_, old_attribute_name)) delattr(object_, old_attribute_name) 没有内置的或标准的库函数来执行此操作。我假设,因为: 正如
def rename_attribute(object_, old_attribute_name, new_attribute_name):
setattr(object_, new_attribute_name, getattr(object_, old_attribute_name))
delattr(object_, old_attribute_name)
没有内置的或标准的库函数来执行此操作。我假设,因为:
- 正如您完全充分的示例所示,这是微不足道的
- 没有通用用例
def rename_attribute(obj, old_name, new_name):
obj.__dict__[new_name] = obj.__dict__.pop(old_name)
您可以使用为原始属性提供外观/重命名 例如:假设您有一个属性
attr
,并且希望将其重命名为new\u attr
,以便在引用new\u attr
时返回或修改attr
class Foo:
def __init__(self, a):
self.attr = a
@property
def new_attr(self):
return self.attr
@new_attr.setter
def new_attr(self, new_value):
self.attr = new_value
为新名称调用属性时,我们有:
if __name__ == '__main__':
f = Foo(2)
print('The renamed attribute is', f.new_attr)
f.new_attr = 5
print('The renamed attribute after using setter method is', f.new_attr)
print('The old attribute is', f.attr)
在输出端:
'The renamed attribute is 2'
'The renamed attribute after using setter method is 5'
'The old attribute is 5'
请注意,attr
始终可供使用,并且new\u attr
始终将引用attr
class Foo:
def __init__(self, a):
self.attr = a
@property
def new_attr(self):
return self.attr
@new_attr.setter
def new_attr(self, new_value):
self.attr = new_value
在查看了文档中的神奇方法之后,我还没有听说过一个。Python中的对象只不过是美化了的名称空间。有一个重命名变量的函数有意义吗?如果你需要这个,也许你应该将数据存储在类似dict的结构中,而不是对象中。好问题。。。大概这并不完全相同,但可能有类似于两个变量的交换可以自然地在一行中完成,因为python的工作方式。我认为有多个因素可以帮助决定我是否应该使用类似dict的结构,这一个不那么紧迫,因为我可以创建rename_属性函数。虽然可能,为什么你想/需要这样做?语义上,同一类的所有实例应该共享相同的属性;区分实例的是属性值,而不是可用的属性。更改属性的名称会破坏对象与其类之间的关系。