• 主页
  • 相册
  • 随笔
  • 目录
  • 存档
Total 244
Search AboutMe

  • 主页
  • 相册
  • 随笔
  • 目录
  • 存档

Python属性与特性

2020-01-22

1. 属性与特性

  • 属性(property)
  • 特性(attribute)

Properties are a special kind of attribute


With a property you have complete control on its getter, setter and deleter methods, which you don’t have (if not using caveats) with an attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class A(object):
_x = 0
'''A._x is an attribute'''

@property
def x(self):
'''
A.x is a property
This is the getter method
'''
return self._x

@x.setter
def x(self, value):
"""
This is the setter method
where I can check it's not assigned a value < 0
"""
if value < 0:
raise ValueError("Must be >= 0")
self._x = value

attribute 包括默认的 getter/setter/deleter,触发内置的 get/set/delete 方法。

property 是特殊的 attribute,可以自定义 getter/setter/deleter 等属性,自己控制 get/set/delete 时触发的方法,也可以不定义来禁止该操作。

另一个例子

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
class Misc():
def __init__(self):
self.test = self.test_func()

def test_func(self):
print 'func running'
return 'func value'

cl = Misc()
print cl.test
print cl.test

func running
func value
func value

# We accessed the attribute twice but our function was fired(触发) only once.Changing the above example to use property will cause attribute's value refresh each time you access it

@property
def test(self):
print 'func running'
return 'func value'

func running
func value
func running
func value

2. 特殊属性

属性意义
__doc__该函数的文档字符串,没有则为 None;不会被子类继承。可写
__name__该函数的名称。可写
__qualname__该函数的 qualified name。 3.3 新版功能.可写
__module__该函数所属模块的名称,没有则为 None。可写
__defaults__由具有默认值的参数的默认参数值组成的元组,如无任何参数具有默认值则为 None。可写
__code__表示编译后的函数体的代码对象。可写
__globals__对存放该函数中全局变量的字典的引用 — 函数所属模块的全局命名空间。只读
__dict__命名空间支持的函数属性。可写
__closure__None 或包含该函数可用变量的绑定的单元的元组。有关 cell_contents 属性的详情见下。只读
__annotations__包含参数标注的字典。字典的键是参数名,如存在返回标注则为 'return'。可写
__kwdefaults__仅包含关键字参数默认值的字典。可写
  • 单元对象具有 cell_contents 属性。这可被用来获取以及设置单元的值

  • qualified name – 限定名称

    一个以点号分隔的名称,显示从模块的全局作用域到该模块中定义的某个类、函数或方法的“路径”

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    >>> class C:
    ... class D:
    ... def meth(self):
    ... pass
    ...
    >>> C.__qualname__
    'C'
    >>> C.D.__qualname__
    'C.D'
    >>> C.D.meth.__qualname__
    'C.D.meth'

3. 示例(python一切皆对象)

1
2
3
4
5
6
7
8
9
10
11
12
>>> x.__class__
<type 'int'>
>>> x.__class__()
0
>>> x.__int__
<method-wrapper '__int__' of int object at 0x00007FFED079A190>
>>> x.__int__()
1
>>> x=2
>>> x.__int__()
2
>>>

4. bool

4.1. 历史

Python也受到了C语言的深刻影响,最初也是用int来做逻辑判断的。 好在Python 2.2版本以后,加入了bool类型。

Python 2.3版本,加入了True与False。 class bool是集成于int的,所以True和False也可以当成1和0

在Python 2中,True与False只是内置常量,可以随意赋值


从Python 3开始,True与False都成为关键字。 是关键字,意味着不能被篡改

1
2
>>> True = 1
SyntaxError: can't assign to keyword

4.2. bool()

bool()不是一个函数,而是一个类的构造操作

1
2
3
4
5
6
7
8
9
10
11
class bool(int)
| bool(x) -> bool
|
| Returns True when the argument x is true, False otherwise.
| The builtins True and False are the only two instances of > the class bool.
| The class bool is a subclass of the class int, and cannot > be subclassed.
|
| Method resolution order:
| bool
| int
| object

它会把一些其它类型的东西,转换成bool类型的True或False。
在很多需要逻辑判断的地方,都会做默认的转换。比如,if a:,就等价于if bool(a):

4.3. not

  • not是一个关键字。有些类似于C语言家族的!,它可以实现逻辑取反操作
  • 需要注意的是,not和is not,是完全不同的。 is not可以看做是一个组合关键字,是对不等的判断。 a is not b,基本等价于not (a is b),只是可读性更高
1
2
3
4
def spam(a, b=None):
if not b: # NO! Use 'b is None' instead
b = []
...

4.4. __bool__()

0、''、[]这些东西,不过也是对象而已,但它们的bool()返回结果不同

1
object.__bool__(self) Called to implement truth value testing and the built-in operation bool(); should return False or True. When this method is not defined, len() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither len() nor bool(), all its instances are considered true.

1
2
3
4
5
6
7
>>> class a:
>>> def __bool__(self):
>>> return False
>>> bool(a())
False
>>> not a()
True

5. 参考资料

  • What’s the difference between a Python “property” and “attribute”? - Stack Overflow
  • 数据模型 — Python 3.8.1 文档
  • Python中的bool · 零壹軒·笔记
  • python之中特性(attribute)与属性(property)有什么区别? - 知乎
  • Program Language
  • Python
  • Advanced
Python方法:实例、类、静态和抽象
脚本与模块
  1. 1. 1. 属性与特性
  2. 2. 2. 特殊属性
    1. 2.1. 3. 示例(python一切皆对象)
    2. 2.2. 4. bool
      1. 2.2.1. 4.1. 历史
      2. 2.2.2. 4.2. bool()
      3. 2.2.3. 4.3. not
      4. 2.2.4. 4.4. __bool__()
  3. 3. 5. 参考资料
© 2024 何决云 载入天数...