[Level 2] Python variable scope (2).
In previous, I wrote a paper for python variable scope.
This time, I try to use python native decorator to implement the same idea.
Wish this helps. regards, Stanley Huang
This time, I try to use python native decorator to implement the same idea.
#!/usr/bin/env python class C(object): def __init__(self): self._name = None self.__age = None @property def name(self): """I'm the 'name' propertage.""" return self._name @name.setter def name(self, value): self._name = value @name.deleter def name(self): del self._name @property def age(self): pass @age.getter def age(self): return self.__age @age.setter def age(self, value): self.__age = value if __name__ == '__main__': c = C() c.name = 1 print c.name print c._name del c.name try: print c.name except AttributeError, e: #print "'C' object has no attribute '_name'" print e c.age = 2 print c.age try: print c.__age except AttributeError, e: #print "'C' object has no attribute '__age'" print e try: del c.age except AttributeError, e: #print "can't delete attribute" print e
$ ./testProperty.py 1 1 'C' object has no attribute '_name' 2 'C' object has no attribute '__age' can't delete attribute $
Wish this helps. regards, Stanley Huang
Comments
Post a Comment