【问题标题】:python special method __getattribute__python特殊方法__getattribute__
【发布时间】:2018-03-16 16:43:59
【问题描述】:

我正在尝试在 python 中使用 getattribute 方法。

class Foo:

  def __init__(self):
     self.x = 3

  def __getattribute__(self, name):
     print("getting attribute %s" %name)
     return super().__getattribute__(self, name)

f = Foo()
f.x

我打印出“获取属性”,但这里还有一个 TypeError:预期 1 个参数,得到 2 个。

那么,这个 sn-p 有什么问题呢?

【问题讨论】:

  • 使用super 时,您不必将self 传递给方法。

标签: python getattribute


【解决方案1】:

super().__getattribute__(self, name) 将其更改为 super().__getattribute__(name)

这将解决您的问题。我希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您的问题是当您呼叫super() 时,您正在传递self

    self 是一个自动填充的变量,无论何时使用。因此,super() 在遇到基本方法时将被分配给self。因此,您实际传递给该方法的是__getattribute__(super(), self, name)。 Python 足够聪明,可以知道在计数中忽略 self,这就是错误显示 2 而不是 3 的原因。

    这将解决您的问题:

    class Foo:
    
      def __init__(self):
         self.x = 3
    
      def __getattribute__(self, name):
         print("getting attribute %s" %name)
         return super().__getattribute__(name)
    
    f = Foo()
    f.x
    

    【讨论】:

      猜你喜欢
      • 2012-10-04
      • 1970-01-01
      • 2015-02-11
      • 1970-01-01
      • 2014-05-14
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 2014-09-11
      相关资源
      最近更新 更多