开发者

How to use descriptors with attributes of instances?

开发者 https://www.devze.com 2023-02-10 15:30 出处:网络
I read the docs and sa开发者_运维技巧w that descriptors had to be used with class attributes only. What would be an acceptable way of using them within instances of that class?

I read the docs and sa开发者_运维技巧w that descriptors had to be used with class attributes only. What would be an acceptable way of using them within instances of that class?

I.e.

class Attribute( object ):
    def __init__(self, value):
        self.value = value

    def __get__(self, obj, objtype):
        print "GETTING"
    def __set__(self,obj,val):
        print "SETTING"

class MyClass( object ):
    def __init__(self):
        self.myname = Attribute( '' )

name = MyClass()
print name.myname


Manipulate them via obj, the second argument to the descriptor's methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消