Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

class - Why is __getattribute__ called in a key/value __dict__ assignment? Python

class Test():
    def __init__(self,age):
        print(self.__dict__)
        self.age=age
        self.__dict__["age"]=6
    def __getattribute__(self,attribute):
        print("Initializing getattribute")
        return object.__getattribute__(self,attribute)
    def __setattr__(self,attribute,value):
        print("Calling setattr")
        return object.__setattr__(self,attribute,value)
test=Test(4)

The code above results in :

Initializing getattribute
{}
Calling setattr
Initializing getattribute

I thought that when we have a attribute assignment, __setattr__ would be called and when a attribute is called directly then the __getattribute__ would be called, but the line : self.__dict__[age]=4, calls __getrattribute__, I bet I'm missing the behavior of __dict__, but I don't know where.

question from:https://stackoverflow.com/questions/66052221/why-is-getattribute-called-in-a-key-value-dict-assignment-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Assigning to self.__dict__["age"] requires an attribute lookup for self.__dict__, and __getattribute__ handles that lookup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...