分类: IT职场
2017-08-17 15:28:35
descr__get__(self, obj, objtype=None) --> value
descr.__set__(self, obj, value) --> None
descr.__delete__(self, obj) --> None
|
class RevealAccess(object):
def __get__(self, obj, objtype):
print('self in RevealAccess: {}'.format(self))
print('self: {}\nobj: {}\nobjtype: {}'.format(self, obj, objtype))
class MyClass(object):
x = RevealAccess()
def test(self):
print('self in MyClass: {}'.format(self))
|
>>> m = MyClass()
>>> m.test()
self in MyClass: <__main__.MyClass object at 0x7f19d4e42160>
>>> m.x
self in RevealAccess: <__main__.RevealAccess object at 0x7f19d4e420f0>
self: <__main__.RevealAccess object at 0x7f19d4e420f0>
obj: <__main__.MyClass object at 0x7f19d4e42160>
objtype:
|
>>> MyClass.x
self in RevealAccess: <__main__.RevealAccess object at 0x7f53651070f0>
self: <__main__.RevealAccess object at 0x7f53651070f0>
obj: None
objtype:
|
data descriptor
instance dict
non-data descriptor
__getattr__()
|
class Account(object):
def __init__(self):
self._acct_num = None
def get_acct_num(self):
return self._acct_num
def set_acct_num(self, value):
self._acct_num = value
def del_acct_num(self):
del self._acct_num
acct_num = property(get_acct_num, set_acct_num, del_acct_num, '_acct_num property.')
|
>>> acct = Account()
>>> acct.acct_num = 1000
>>> acct.acct_num
1000
|
class Account(object):
def __init__(self):
self._acct_num = None
@property
# the _acct_num property. the decorator creates a read-only property
def acct_num(self):
return self._acct_num
@acct_num.setter
# the _acct_num property setter makes the property writeable
def set_acct_num(self, value):
self._acct_num = value
@acct_num.deleter
def del_acct_num(self):
del self._acct_num
|
class Person(object):
def addProperty(self, attribute):
# create local setter and getter with a particular attribute name
getter = lambda self: self._getProperty(attribute)
setter = lambda self, value: self._setProperty(attribute, value)
# construct property attribute and add it to the class
setattr(self.__class__, attribute, property(fget=getter, \
fset=setter, \
doc="Auto-generated method"))
def _setProperty(self, attribute, value):
print("Setting: {} = {}".format(attribute, value))
setattr(self, '_' + attribute, value.title())
def _getProperty(self, attribute):
print("Getting: {}".format(attribute))
return getattr(self, '_' + attribute)
>>> user = Person()
>>> user.addProperty('name')
>>> user.addProperty('phone')
>>> user.name = 'john smith'
Setting: name = john smith
>>> user.phone = '12345'
Setting: phone = 12345
>>> user.name
Getting: name
'John Smith'
>>> user.__dict__
{'_phone': '12345', '_name': 'John Smith'}
|
class StaticMethod(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, objtype=None):
return self.f
|
class MyClass(object):
@StaticMethod
def get_x(x):
return x
print(MyClass.get_x(100)) # output: 100
|
class ClassMethod(object):
def __init__(self, f):
self.f = f
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
def newfunc(*args):
return self.f(klass, *args)
return newfunc
|
In [1]: class Test(object):
...: def __getattribute__(self, item):
...: print('call __getattribute__')
...: return super(Test, self).__getattribute__(item)
...: def __getattr__(self, item):
...: return 'call __getattr__'
...:
In [2]: Test().a
call __getattribute__
Out[2]: 'call __getattr__'
|
class Storage(dict):
""" A Storage object is like a dictionary except `obj.foo` can be used in addition to `obj['foo']`. """
def __getattr__(self, key):
try:
return self[key]
except KeyError as k:
raise AttributeError(k)
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError as k:
raise AttributeError(k)
def __repr__(self):
return '
|
>>> s = Storage(a=1)
>>> s['a']
1
>>> s.a
1
>>> s.a = 2
>>> s['a']
2
>>> del s.a
>>> s.a
...
AttributeError: 'a'
__getitem__
|
class MyList(object):
def __init__(self, *args):
self.numbers = args
def __getitem__(self, item):
return self.numbers[item]
my_list = MyList(1, 2, 3, 4, 6, 5, 3)
print my_list[2]
|
class CaseInsensitiveDict(dict):
@property
def lower_keys(self):
if not hasattr(self, '_lower_keys') or not self._lower_keys:
self._lower_keys = dict((k.lower(), k) for k in self.keys())
return self._lower_keys
def _clear_lower_keys(self):
if hasattr(self, '_lower_keys'):
self._lower_keys.clear()
def __contains__(self, key):
return key.lower() in self.lower_keys
def __getitem__(self, key):
if key in self:
return dict.__getitem__(self, self.lower_keys[key.lower()])
def __setitem__(self, key, value):
dict.__setitem__(self, key, value)
self._clear_lower_keys()
def __delitem__(self, key):
dict.__delitem__(self, key)
self._lower_keys.clear()
def get(self, key, default=None):
if key in self:
return self[key]
else:
return default
|
>>> d = CaseInsensitiveDict()
>>> d['ziwenxie'] = 'ziwenxie'
>>> d['ZiWenXie'] = 'ZiWenXie'
>>> print(d)
{'ZiWenXie': 'ziwenxie', 'ziwenxie': 'ziwenxie'}
>>> print(d['ziwenxie'])
ziwenxie
# d['ZiWenXie'] => d['ziwenxie']
>>> print(d['ZiWenXie'])
ziwenxie
|