Created
November 30, 2015 08:17
-
-
Save tlkahn/3b24238c1aeb16069d14 to your computer and use it in GitHub Desktop.
python descriptor example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Desc(object): | |
| def __get__(self, obj, klass): | |
| return lambda x: x+1 | |
| class Desc2(object): | |
| def __get__(self, obj, klass): | |
| print "getting from Desc2" | |
| return lambda: obj.name + " guo" | |
| class A(object): | |
| # def add_surname(f): | |
| # def wrapper(self, surname): | |
| # return f(self) + surname | |
| # return wrapper | |
| # @add_surname | |
| # def getname(self): | |
| # return self.name | |
| def __init__(self, name): | |
| self.name = name | |
| adder = Desc() | |
| show_name = Desc2() | |
| # def __get__(self, obj, objtype): | |
| # print "retrieving A instance value" | |
| # return self.name | |
| # def __set__(self, obj, value): | |
| # print "setting A instance value" | |
| # title = "ceo" | |
| a = A("josh") | |
| a.show_name = "yes" | |
| del a.show_name | |
| print a.show_name() | |
| # print a.adder(2) | |
| # a.__dict__['show_name'] = 'something' | |
| # print a.show_name | |
| # print a.show_name() | |
| # desc = A.__dict__['show_name'] | |
| # print desc.__get__(a, A)() | |
| # class B: | |
| # value = A("josh") | |
| # a = A("josh").getname('guo') | |
| # print a | |
| # print A("josh").title | |
| # a = A() | |
| # print aglobal name 'self' is not defined.name('yo') | |
| # print a | |
| # b = B() | |
| # print b.value | |
| # class RevealAccess(object): | |
| # """A data descriptor that sets and returns values | |
| # normally and prints a message logging their access. | |
| # """ | |
| # def __init__(self, initval=None, name='var'): | |
| # self.val = initval | |
| # self.name = name | |
| # def __get__(self, obj, objtype): | |
| # print 'Retrieving', self.name | |
| # return self.val | |
| # def __set__(self, obj, val): | |
| # print 'Updating', self.name | |
| # self.val = val | |
| # class MyClass(object): | |
| # x = RevealAccess(10, 'var "x"') | |
| # y = 5 | |
| # m = MyClass() | |
| # print m.x |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment