python面向对象--描述符和属性

python面向对象–描述符和属性

python中的私有属性

python中没有访问限制的描速符.通过__符号来实现

Ex:

1
2
class MyClass(object):
__secret_value = 1
1
2
3
4
5
6
7
In [3]: m.__secret_value
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-3-3a26128381d5> in <module>()
----> 1 m.__secret_value
AttributeError: 'MyClass' object has no attribute '__secret_value'

查看属性

1
2
3
4
In [4]: dir(m)
Out[4]:
['_MyClass__secret_value',
'__class__',

其实也并不是真正意义上的私有属性.

描述符

描述符用来自定义在引用一个对象上的特性时所应该完成的事情.
基于如下三个特殊的方法

  • __set__ 在任何属性被设置时调用,setter;
  • __get__ 在任何属性被读取的时候被调用,getter;
  • __delete__
    这些方法都在 __dict__之前被调用.

其实就是通过一个类,对另外一个类的某个属性进行控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class UpperString(object):
def __init__(self):
self._val = ""
def __get__(self, instance, klass):
return self._val
def __set__(self, instance, value):
self._val = value.upper()
class MyClass(object):
attribute = UpperString()
mc = MyClass()
mc.attribute = "my value"
print mc.attribute

自省描述符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class API(object):
def _print_values(self, obj):
def _print_value(key):
if key.startswith('_'):
return ''
value = getattr(obj, key)
if not hasattr(value, 'im_func'):
doc = type(value).__name__
else:
if value.__doc__ is None:
doc = 'no docstring'
else:
doc = value.__doc__
return " %s : %s" % (key, value)
res = [_print_value(el) for el in dir(obj)]
return '\n'.join([el for el in res if el != ""])
def __get__(self, instance, klass):
if instance is not None:
return self._print_values(instance)
else:
return self._print_values(klass)
class MyClass(object):
__doc__ = API()
def __init__(self):
self.a = 2
def meth(self):
'''
my method
'''
return 1
print MyClass.__doc__
instance = MyClass()
print "========"
print instance.__doc__

output:

1
2
3
4
meth : <unbound method MyClass.meth>
========
a : 2
meth : <bound method MyClass.meth of <__main__.MyClass object at 0x7fe3295bcad0>>

元描述符

属性

属性提供了一个内建的描述符类型,属性采用fget和3个可选的参数–fset, fdeldoc

这个概念很少遇到

坚持技术分享,您的支持将鼓励我继续创作!