質問

I know what is property/descriptor and decorator. But I have some hard time getting this point.

class Person(object):
    @property
    def name(self, func):
        pass

    print("-- before setting -- ", name)

    @name.setter   # <---- what `name` object should be here
    def name(self, v):
        self._fn, self._ln = v.split(" ")

    print("-- before getting -- ", name)

    @name.getter  # <---- and here
    def name(self):
        return self._fn + " " + self._ln

    print("-- all done -- ", name) # <---- and here

Descriptor is class level object. So @name.setter and @name.getter should get same name descriptor object. When I add print statements after setter and getter, I am getting following result:

('-- before setting -- ', <property object at 0x7fc1b0218f70>)  # (a)
('-- before getting -- ', <property object at 0x7fc1b0218fc8>) # (b)
('-- all done -- ', <property object at 0x7fc1b0218f70>) #(c)

(a) and (c) statements have same property object but (b) doesn't.

Can somebody explain me why is that or Am I missing something?

役に立ちましたか?

解決

They're 3 different property objects; the 3rd is just reusing the memory allocated for the first, since the first has been collected. When you use

@name.getter

or

@name.setter

the decorator returns a new property object reflecting the getter or setter you defined, which is then bound to the name of the function you're defining. Since the name of the function you're defining is name, it replaces the old name property.

他のヒント

The decorators recreate the property object each time, combining the new information with the existing property. That the object IDs are the same in (a) and (c) is coincidence.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top