Python的特殊属性和魔法函数
python中有很多以下划线开头和结尾的特殊属性和魔法函数,它们有着很重要的作用。
1.__doc__:说明性文档和信息,python自建,不需要我们定义。
# -*- coding:utf- -*- class Person:
"""这里是描述性信息"""
def func(self):
pass if __name__ == '__main__':
print(Person.__doc__)
2.__init__():实例化方法,创建实例时自动执行。
# -*- coding:utf- -*- class Person:
def __init__(self):
print("自动执行了__init__()方法") if __name__ == '__main__':
person = Person()
3.__module__和__class__
__module__:当前操作的对象属于哪一个模块,__class__:当前操作的对象属于哪一个类。
# -*- coding:utf- -*- class Person:
def __init__(self):
print("自动执行了__init__()方法") if __name__ == '__main__':
person = Person()
print(person.__module__)
print(person.__class__) -------输出--------
__main__
<class '__main__.Person'>
4.__del__():当对象在内存中被释放时,自动执行该方法,该方法无限自定义,除非我们想要在对象释放时执行一些操作。
# -*- coding:utf- -*-
class Person:
def __del__(self):
print("我被回收了")
if __name__ == '__main__':
person = Person()
5.__call__():如果一个类编写了该方法,则该类的实例后面加括号时会调用此方法。
# -*- coding:utf- -*-
class Person:
def __call__(self, *args, **kwargs):
print("执行了__call__")
if __name__ == '__main__':
person = Person()
person()
print(callable(Person))
可以通过callable()函数判断一个类是否为可执行的。
6.__dict__:列出类或者对象中的所有成员。
# -*- coding:utf- -*- class Person:
country = "中国"
def __init__(self, name, age):
self.name = name
self.age = age def func(self):
print("func") if __name__ == '__main__':
print(Person.__dict__)
person = Person("zhangsan", )
print(person.__dict__) -------输出结果--------
{'country': '中国', '__init__': <function Person.__init__ at 0x00000247F6218B70>, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, 'func': <function Person.func at 0x00000247F6218BF8>, '__doc__': None}
{'age': , 'name': 'zhangsan'}
7.__str__():如果一个类定义了这个方法,则在打印对象时会自动执行该方法。
# -*- coding:utf- -*-
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return "name:"+self.name+"----age:"+self.age
if __name__ == '__main__':
person = Person("zhangsan", "")
print(person)
------输出结-------
name:zhangsan----age:
8.__getitem__(),__setitem()__.__delitem__():取数据,设置数据,删除数据。
aa = 标识符[] # 执行__getitem__()
标识符[] = bb # 执行__setitem__()
del 标识符[] # 执行__delitem__()
# -*- coding:utf- -*- class Person:
def __setitem__(self, key, value):
print("执行了__setitem__()") def __getitem__(self, item):
print("执行了__getitem__()") def __delitem__(self, key):
print("执行了__delitem__()") if __name__ == '__main__':
person = Person()
r = person['a']
person['a'] = "AAA"
del person['a'] --------输出结果-------
执行了__getitem__()
执行了__setitem__()
执行了__delitem__()
9.__iter__():如果想让自定义的类的对象可以被迭代,则需要定义该方法,并返回一个可迭代的对象。
# -*- coding:utf- -*-
class Person:
def __iter__(self):
yield
yield
yield
if __name__ == '__main__':
person = Person()
for p in person:
print(p)
------输出结果-------
10.__len__():获取对象的长度。
In []: 'ABCDE'.__len__()
Out[]: In []: len('ABCDE')
Out[]:
11.__repr__():返回开发可以看到的字符串,与__str__()的区别是__str__()返回用户可以看到的字符串,通常两者代码一样。
# -*- coding:utf- -*-
class Person:
def __init__(self, name):
self.name = name
def __str__(self):
return "this is %s" % self.name
__repr__ = __str__
if __name__ == '__main__':
person = Person("张三")
print(person)
print(person.__repr__())
------输出结果-------
this is 张三
this is 张三
12.__add__:加法,__sub__:减法,__mul__:乘法,__div__:除法,__mod__:求与运算,__pow__:幂运算
class Calculator:
def __init__(self, a):
self.a = a
def __add__(self, other):
return self.a + other.a
if __name__ == '__main__':
a = Calculator()
b = Calculator()
print(a + b)
13.__author__:表示作者信息。
# -*- coding:utf- -*-
__author__ = "boxiaoyuan"
class Calculator:
def show(self):
print(__author__)
if __name__ == '__main__':
a = Calculator()
a.show()
14.__slots__:可以限制实例的变量只可以添加哪些属性。
# -*- coding:utf- -*- def show(self):
print("hello world") class Person: def __init__(self):
pass __slots__ = ("name","age") p = Person()
p.name = "zhangsan"
p.age = ""
# p.sex = "男"
Person.show = show # 无法限制为类添加方法
p.show()
Python的特殊属性和魔法函数的更多相关文章
- PythonI/O进阶学习笔记_2.魔法函数
前言: 本文一切观点和测试代码是在python3的基础上. Content: 1.什么是魔法函数,魔法函数__getitem__在python中应用. 2.python的数据模型和数据模型这种设计对p ...
- 【python学习笔记】9.魔法方法、属性和迭代器
[python学习笔记]9.魔法方法.属性和迭代器 魔法方法:xx, 收尾各有两个下划线的方法 __init__(self): 构造方法,创建对象时候自动执行,可以为其增加参数, 父类构造方法不会被自 ...
- Python的魔法函数系列 __getattrbute__和__getattr__
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys __metaclass__ = type """ _ ...
- Python魔法函数
python中定义的以__开头和结尾的的函数.可以随意定制类的特性.魔法函数定义好之后一般不需要我们自己去调用,而是解释器会自动帮我们调用. __getitem__(self, item) 将类编程一 ...
- python魔法函数之__getattr__与__getattribute__
getattr 在访问对象的属性不存在时,调用__getattr__,如果没有定义该魔法函数会报错 class Test: def __init__(self, name, age): self.na ...
- python进阶之魔法函数
__repr__ Python中这个__repr__函数,对应repr(object)这个函数,返回一个可以用来表示对象的可打印字符串.如果我们直接打印一个类,向下面这样 class A(): ...
- gj3 Python数据模型(魔法函数)
3.1 什么是魔法函数 类里面,实现某些特性的内置函数,类似 def __xx__(): 的形式. 不要自己定义XX,并不是和某个类挂钩的 class Company(object): def __i ...
- python内置函数和魔法函数
内置方法:Python中声明每一个类系统都会加上一些默认内置方法,提供给系统调用该类的对象时使用.比如需要实例化一个对象时,需要调用该类的init方法:使用print去打印一个类时,其实调用的是str ...
- python魔法函数__dict__和__getattr__的妙用
python魔法函数__dict__和__getattr__的妙用 __dict__ __dict__是用来存储对象属性的一个字典,其键为属性名,值为属性的值. 既然__dict__是个字典那么我们就 ...
随机推荐
- 八 Connect API 连接器
Connect API: 实现一个连接器(connector),不断地从一些数据源系统拉取数据到kafka,或从kafka推送到宿系统(sink system). 大多数Connect使用者不需要直接 ...
- linux lcd设备驱动剖析四
在"linux lcd设备驱动剖析二"文章中,我们详细分析了s3c24xxfb_probe函数. 文章链接:http://blog.csdn.net/lwj103862095/ar ...
- js中的Math
js中的Math Math.round 取最接近的整数 Math.round(-2.7) // -3 Math.ceil 向上取整 Math.ceil(1.1) // 2 Math.floor 向下取 ...
- Windows环境下使用.bat安装和卸载服务
一.Windows环境下使用.bat安装和卸载服务 win7环境 例子中“”Valwell.Dms.HttpService.exe“”为服务程序名称 安装服务 %SystemRoot%\Microso ...
- Centos7 第三方仓库 yum 方式安装 PHP7.2
1.卸载原先安装的PHP yum remove php rpm -qa|grep php #列出所有的php相关的rpm包 rpm -e xxx #xxx指的是上一个命令列出的rpm包的包名,复制即可 ...
- 聚类 高维聚类 聚类评估标准 EM模型聚类
高维数据的聚类分析 高维聚类研究方向 高维数据聚类的难点在于: 1.适用于普通集合的聚类算法,在高维数据集合中效率极低 2.由于高维空间的稀疏性以及最近邻特性,高维的空间中基本不存在数据簇. 在高维聚 ...
- Unity调试设置
[Unity调试设置] 1.Mac中,"Unity"->"Preferences...". Windows中,"Edit"->& ...
- 分布式文件系统MFS(moosefs)实现存储共享
分布式文件系统MFS(moosefs)实现存储共享(第二版) 作者:田逸(sery@163.com) 由于用户数量的不断攀升,我对访问量大的应用实现了可扩展.高可靠的集群部署(即lvs+keepali ...
- 类型或命名空间名称“Interop”在类或命名空间“Microsoft.Office”中不存在(是否缺少程序集引用?)
准备用C#编写Web程序,生成Excel报表,在使用下面语句时报错. using Microsoft.Office.Interop.Excel; 报错信息:类型或命名空间名称“Interop”在类或命 ...
- Hyperledger Fabric Chaincode解析
首先看下Blockchain结构,除了header指向下一个block的hash value外,block是由一组transaction构成, Transactions --> Blocks - ...