Skip to main content
 首页 » 编程设计

python之使用 getattr [ python ] 在实例上调用方法

2025年05月04日12yyy_WW

我试图编写一些代码来检查项目是否具有某些属性,并调用它们。我尝试使用 getattr 来做到这一点,但修改不会是永久性的。我做了一个“虚拟”类来检查这个。 这是我在类(class)中使用的代码:

 
class X:                                          
   def __init__(self): 
     self.value = 90   
   def __get(self):    
     return self.value 
   def __set(self,value): 
     self.value = value   
   value = property(__get,__set) 
 
x = X() 
print x.value # this would output 90 
getattr(x,"value=",99) # when called from an interactive python interpreter this would output 99 
print x.value # this is still 90 ( how could I make this be 99 ? )  

谢谢!

请您参考如下方法:

你需要做类似的事情

class X:                                          
   def __init__(self): 
     self._value = 90   
 
   def _get(self):    
     return self._value 
 
   def _set(self, value): 
     self._value = value   
 
   value = property(_get, _set) 

请注意,“内部”变量的名称必须与属性名称不同(我使用了 _value)。

然后,

setattr(x, 'value', 99) 

应该可以。