Python的“__setattr__”和“__getattribute__”的困惑

问题描述 投票:0回答:1

什么是错的代码?

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这些方法

python python-internals
1个回答
3
投票

但上面的代码不会打印任何东西

错误。它崩溃了无限递归。

__getattribute__,当你想记录/截取呼叫,在某些时候,你仍然希望得到原来的方法来获得属性。和self.__dict__[name]调用__getattribute__所以它没有这样做的正确方法。

什么你又试图调用此方法,你会得到无限递归。调用父/基方法代替:

# 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__返回(因为它只是打印到控制台,并含蓄地返回None)。也许一个例外会是一个更好的主意。

© www.soinside.com 2019 - 2024. All rights reserved.