【问题标题】:calling methods on an instance with getattr [ python ]使用 getattr [ python ] 在实例上调用方法
【发布时间】:2010-10-03 19:25:30
【问题描述】:

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


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 ? ) 

谢谢!

【问题讨论】:

    标签: python dynamic attributes properties


    【解决方案1】:

    你需要做类似的事情

    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)
    

    应该可以。

    【讨论】:

    • 这就是我想要的!谢谢!
    • 我是 Python 新手,在什么情况下你会采用这种方法?
    • 我正在编写一个类,为 BeautifulSoup 添加一些 XPath 支持,我需要检查是否有一个作为字符串传递的属性。
    • 在 2.x 中,这仅在从对象显式继承时才有效。 X 类(对象):...
    • @Kev:作为 SO 中的顶级问题,在 cmets 中很难解决这样的问题。
    【解决方案2】:
    getattr(x,"value=",99)
    

    返回 99,因为 x 没有属性“value=”(注意等号),因此 getattr 返回提供的默认值 (99)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-11
      • 2013-11-03
      • 2012-11-02
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 2021-06-30
      • 2014-10-18
      相关资源
      最近更新 更多