代码之家  ›  专栏  ›  技术社区  ›  Lokesh Agrawal

Python“\uuuuu setattr\uuuuuuuuuuu”和“\uuuuuuu getattribute\uuuuuuuuuuuuuuuuuuuuuuuuu”混淆

  •  0
  • Lokesh Agrawal  · 技术社区  · 7 年前

    class Spam(object):
    
        def __init__(self, a, b):
            self.a = a
            self.b = b
    
        # using this to mark field "c" as deprecated. As per my understanding this gets called only for fields that do not exist.
        def __getattr__(self, c):
            print("Deprecated")
    
        # using this to manipulate the value before storing
        def __setattr__(self, name, value):
            self.__dict__[name] = value + 1
    
        # interceptor to allows me to define rules for whenever an attribute's value is accessed
        def __getattribute__(self, name):
            return self.__dict__[name] 
    
    spam = Spam(10, 20)
    
    print(spam.a)
    print(spam.b)
    print(spam.c)
    

    但是上面的代码没有打印任何内容。这里出了什么问题,有人能帮我理解吗?我在书中读到了这些方法 https://rszalski.github.io/magicmethods/#access

    1 回复  |  直到 7 年前
        1
  •  3
  •   Jean-François Fabre    7 年前

    但是上面的代码没有打印任何内容

    错误的它在无限递归中崩溃。

    在里面 __getattribute__ ,当您想要记录/截获调用时,在某些时候您仍然希望获得原始方法来获取属性。和 self.__dict__[name] 电话 所以这不是正确的做法。

    # interceptor to allows me to define rules for whenever an attribute's value is accessed
    def __getattribute__(self, name):
        return object.__getattribute__(self,name)  # or super(Spam,self).__getattribute__(name)
    

    上面印着:

    11
    21
    Deprecated
    None
    

    None 由返回 __getattr__ (因为它只是打印到控制台并隐式返回 没有一个