能把一个对象用字符串的形式表达出来以便辨认,这就是“字符串表示形式”。
class Test():
def __init__(self, name):
self.name = name
def __repr__(self):
return '这个类的名字是: % s' % self.name
str = Test('科學')
print(str) # 这个类的名字是: 科学
当使用print输出对象的时候,若定义了__str__(self)方法,打印对象时就会从这个方法中打印出return的z字符串数据。
_formats = {'ymd': '{d.year}-{d.month}-{d.day}', 'mdy': '{d.month}/{d.day}/{d.year}'}
class Date:
def __init__(self, year, month, day):
self.year = year
self.month = month
self.day = day
def __format__(self, code):
if code == '':
code = 'ymd'
fmt = _formats[code]
return fmt.format(d=self)
d = Date(2018, 8, 8)
r = format(d)
这个方法返回所给键对应的值。当对象是序列时,键是整数。当对象是映射时(字典),键是任意值。
class Fib(): #定义类Fib
def __init__(self,start=0,step=1):
self.step=step
def __getitem__(self, key): #定性__getitem__函数,key为类Fib的键
a = key+self.step
return a #当按照键取值时,返回的值为a
s=Fib()
s[1] #返回2 ,因为类有 __getitem__方法,所以可以直接通过键来取对应的值
setitem(self,key,value)方法应该以与键相关联的方式存储值,以便之后能够使用__setitem__来获取。当然,这个对象可变时才需要实现这个方法。
class Tag:
def __init__(self):
self.change={'python':'This is python',
'php':'PHP is a good language'}
def __getitem__(self, item):
print('调用getitem')
return self.change[item]
def __setitem__(self, key, value):
print('调用setitem')
self.change[key]=value
a=Tag()
print(a['php'])
a['php']='PHP is not a good language'
print(a['php'])
"""
输出:
调用getitem
PHP is a good language
调用setitem
调用getitem
PHP is not a good language
"""
这个方法在对对象的组成部分使用__del__语句的时候被调用,应删除与key相关联的值。同样,仅当对象可变的时候,才需要实现这个方法。
class Tag:
def __init__(self):
self.change={'python':'This is python',
'php':'PHP is a good language'}
def __getitem__(self, item):
print('调用getitem')
return self.change[item]
def __setitem__(self, key, value):
print('调用setitem')
self.change[key]=value
def __delitem__(self, key):
print('调用delitem')
del self.change[key]
a=Tag()
print(a['php'])
del a['php']
print(a.change)
"""
输出:
调用getitem
PHP is a good language
调用delitem
{'python': 'This is python'}
"""
判断元素是否在序列中
class BeiMenChuiXue:
def __init__(self, name):
self.name = name
def __contains__(self, item):
return item in self.name
if __name__ == '__main__':
name = BeiMenChuiXue("beimenchuixue")
print('bei' in name)
"""
for … in… 这个语句其实做了两件事:
1. 第一件事是获得一个可迭代器,即调用了__iter__()函数。
2. 第二件事是循环的过程,循环调用__next__()函数。
对于test这个类来说,它定义了__iter__和__next__函数,所以是一个可迭代的类,也可以说是一个可迭代的对象(Python中一切皆对象)。
"""
class test():
def __init__(self,data=1):
self.data = data
def __iter__(self):
return self
def __next__(self):
if self.data > 5:
raise StopIteration
else:
self.data+=1
return self.data
for item in test(3):
print(item)
class test():
def __init__(self,data=1):
self.data = data
def __next__(self):
if self.data > 5:
raise StopIteration
else:
self.data+=1
return self.data
t = test(3)
for i in range(3):
print(t.__next__())
def fib(end = 1000):
prev,curr=0,1
while curr < end:
yield curr
prev,curr=curr,curr+prev
print(list(fib()))
init()方法,在创建一个对象时默认被调用,不需要手动调用
init(self)中的self参数,不需要开发者传递,python解释器会自动把当前的对象引用传递过去在类内部获取 属性 和 实例方法,通过self获取;
在类外部获取 属性 和 实例方法,通过对象名获取。如果一个类有多个对象,每个对象的属性是各自保存的,都有各自独立的地址;
但是实例方法是所有对象共享的,只占用一份内存空间。类会通过self来判断是哪个对象调用了实例方法。
在实例 (通过
__new__()
) 被创建之后,返回调用者之前调用。其参数与传递给类构造器表达式的参数相同。一个基类如果有__init__()
方法,则其所派生的类如果也有__init__()
方法,就必须显式地调用它以确保实例基类部分的正确初始化;例如:super().__init__([args...])
.因为对象是由
__new__()
和__init__()
协作构造完成的 (由__new__()
创建,并由__init__()
定制),所以__init__()
返回的值只能是None
,否则会在运行时引发TypeError
。
class Cat:
- 创建init方法 参数
def __init__(self, name, age):
self.name = name(增加实例)
self.age = age
def __str__(self): - 对init方法调用
return "%s的年龄%d" % (self.name, self.age)
def sing(self): - 创建方法
print("猫在唱歌")
def dance(self):
print("猫在跳舞")
tom = Cat("老王的猫", 40) - 创建对象
tom.sing() - 调用对象中的方法
tom.dance()
print(tom)
调用以创建一个 cls 类的新实例。
__new__()
是一个静态方法 (因为是特例所以你不需要显式地声明),它会将所请求实例所属的类作为第一个参数。其余的参数会被传递给对象构造器表达式 (对类的调用)。__new__()
的返回值应为新对象实例 (通常是 cls 的实例)。典型的实现会附带适宜的参数使用
super().__new__(cls[, ...])
,通过超类的__new__()
方法来创建一个类的新实例,然后根据需要修改新创建的实例再将其返回。如果
__new__()
未返回一个 cls 的实例,则新实例的__init__()
方法就不会被执行。
__new__()
的目的主要是允许不可变类型的子类 (例如 int, str 或 tuple) 定制实例创建过程。它也常会在自定义元类中被重载以便定制类创建过程。
#上下文管理协议;
#之前说过文件的open,可以使用 with open() as f :
#其实,这个就是利用了上下文管理协议;上下文管理协议的本质,就是__enter__()、__exit__()两个方法的触发;
class Foo:
def __init__(self,filename):
self.filename=filename
def __enter__(self):
print("执行__enter__()")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("执行__exit__()")
print(exc_type)
print(exc_val)
print(exc_tb)#上面三个参数的打印只是为了看参数的值;
# 当with ... as...代码块没有异常时,这三个参数为None;
#当with ... as...代码块有异常时,这三个参数分别有对应的值(可运行代码查看值的详情)
return True #返回值True,会吞掉with ... as...代码块的异常,并且结束代码块运行,但是代码块之外的代码要继续运行
#若,没有返回值、或者返回值不为True,一遇到with ... as...代码块的异常,
# 会立即抛出异常,结束所有代码的运行,包括代码块之外的代码
if __name__ == '__main__':
with Foo("test.txt") as f:
print("1")
print(b)
print("3")
print("4")
兜底函数_getattr_,当我们访问一个不存在的属性的时候,会抛出异常,提示我们不存在这个属性。访问一个不存在的属性的最后落脚点,作为异常抛出的地方提示出错。
class A(object):
def __init__(self, value):
self.value = value
def __getattr__(self, item):
print "into __getattr__"
return "can not find"
a = A(10)
print a.value
# 10
print a.name
# into __getattr__
# can not find
在对一个属性设置值的时候,会调用到这个函数,每个设置值的方式都会进入这个方法。
class A(object):
def __init__(self, value):
print("into __init__")
self.value = value
def __setattr__(self, name, value):
print("into __setattr__")
if value == 10:
print("from __init__")
object.__setattr__(self, name, value)
a = A(10)
print(a.value)
# into __init__
# into __setattr__
# from __init__
# 10
a.value = 100
print(a.value)
# into __setattr__
# 100
class A(object):
def __init__(self, value):
self.value = value
def __setattr__(self, name, value):
self.__dict__[name] = value
a = A(10)
print a.value
# 10
class A(object):
def __init__(self, value):
self.value = value
def __setattr__(self, name, value):
self.name = value
__delattr__是个删除属性的方法
class A(object):
def __init__(self, value):
self.value = value
def __delattr__(self, item):
object.__delattr__(self, item)
def __getattr__(self, item):
return "when can not find attribute into __getattr__"
a = A(10)
print a.value
# 10
del a.value
print a.value
# when can not find attribute into __getattr__
dict 是类的内置属性,用于以字典的形式存储类里的属性,也就是存储那些 self.xxx 的属性
class People(object):
def __init__(self):
self.name = 'Tom'
self.age = 23
obj = People()
print obj.__dict__
# {'age': 23, 'name': 'Tom'}
+= 背后的特殊方法是 _iadd_ (用于“就地加法”)。但是如果一个类没有实现这个方法的话,Python 会退一步调用 __add__
将文档写在程序里,是LISP中的一个特色,Python也借鉴过。每个函数都是一个对象,每个函数对象都是有一个__doc__的属性,函数语句中,如果第一个表达式是一个string,这个函数的__doc__就是这个string,否则__doc__是None。
允许一个类的实例像函数一样被调用。实质上说,这意味着 x() 与 x.__call__() 是相同的。注意 __call__ 参数可变。这意味着你可以定义 __call__ 为其他你想要的函数,无论有多少个参数。
bytes() 函数调用它获取对象的字节序列表示形式
作用是让抽象基类识别没有注册为子类的类,你可以根据需要做简单的或者复杂的测试——标准库的做法只是检查方法名称。
返回下一个可用的元素
定义列表__all__,只有在__all__中的名称才能通过*导入
实现反向迭代序列中的元素(字符串、列表、元组序列)
__reversed__()
特殊方法返回容器中元素的个数
判断对象(object)的真假,并返回True或False
abs()函数可返回一个数的绝对值,()中参数可以是整数或浮点数,如果参数是复数,则返回这个复数的模
内置的 dir() 函数能够返回由对象所定义的名称列表。
# operator 模块中定义的部分函数(省略了以 _ 开头的名称,因为它们基本上是实现细节)
[name for name in dir(operator) if not name.startswith('_')]
"""
['abs', 'add', 'and_', 'attrgetter', 'concat', 'contains','countOf', 'delitem', 'eq', 'floordiv', 'ge', 'getitem', 'gt','iadd', 'iand', 'iconcat', 'ifloordiv', 'ilshift', 'imod', 'imul','index', 'indexOf', 'inv', 'invert', 'ior', 'ipow', 'irshift','is_', 'is_not', 'isub', 'itemgetter', 'itruediv', 'ixor', 'le','length_hint', 'lshift', 'lt', 'methodcaller', 'mod', 'mul', 'ne','neg', 'not_', 'or_', 'pos', 'pow', 'rshift', 'setitem', 'sub','truediv', 'truth', 'xor']
"""
type()
函数用于获取对象的类型。
用来判断一个函数是否是一个已知的类型
从序列a中随机抽取n个元素,并将n个元素生以list形式返回。
打乱序列里面的元素,并随机排列
import random
random.shuffle(alist)
用来遍历一个集合对象,它在遍历的同时还可以得到当前元素的索引位置。
用以构建只有少数属性但是没有方法的对象
import collections
Card = collections.namedtuple('Card', ['rank', 'suit'])
ranks = [str(n) for n in range(2, 11)] + list('JQKA')
suits = 'spades diamonds clubs hearts'.split()
cards = [Card(rank, suit) for suit in self.suits for rank in self.ranks]
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position * ' |'
print(ROW_FMT.format(needle, position, offset))
if __name__ == '__main__':
if sys.argv[-1] == 'left':
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print('DEMO:', bisect_fn.__name__)
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn)
"""
DEMO: bisect
haystack -> 1 4 5 6 8 12 15 20 21 23 23 26 29 30
31 @ 14 | | | | | | | | | | | | | |31
30 @ 14 | | | | | | | | | | | | | |30
29 @ 13 | | | | | | | | | | | | |29
23 @ 11 | | | | | | | | | | |23
22 @ 9 | | | | | | | | |22
10 @ 5 | | | | |10
8 @ 5 | | | | |8
5 @ 3 | | |5
2 @ 1 |2
1 @ 1 |1
0 @ 0 0
"""
如果给这个类一个映射,它会返回一个只读的映射视图。虽然是个只读视图,但是它是动态的。这意味着如果对原映射做出了改动,我们通过这个视图可以观察到,但是无法通过这个视图对原映射做出修改。
from types import MappingProxyType
d = {1:'A'}
d_proxy = MappingProxyType(d)
d_proxy # mappingproxy({1: 'A'})
d_proxy[1] # 'A'
d[2] = 'B'
d_proxy # mappingproxy({1: 'A', 2: 'B'})
d_proxy[2] # 'B'
all(iterable) 如果 iterable 的每个元素都是真值,返回 True;all([]) 返回True。
any(iterable) 只要 iterable 中有元素是真值,就返回 True;any([]) 返回False。
callable() 函数用于检查一个对象是否是可调用的。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功.对于函数, 方法, lambda 函式, 类, 以及实现了 call 方法的类实例, 它都返回 True。
[callable(obj) for obj in (abs, str, 13)]
# [True, True, False]
根据元组的某个字段给元组列表排序
使用 itemgetter 排序一个元组列表
>>> metro_data = [
... ('Tokyo', 'JP', 36.933, (35.689722, 139.691667)),
... ('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
... ('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
... ('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
... ('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
... ]
>>>
>>> from operator import itemgetter
>>> for city in sorted(metro_data, key=itemgetter(1)):
... print(city)
...
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833))
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889))
('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
('Mexico City', 'MX', 20.142, (19.433333, -99.133333))
('New York-Newark', 'US', 20.104, (40.808611, -74.020386))
把多个参数传给 itemgetter,它构建的函数会返回提取的值构成的元组:
>>> cc_name = itemgetter(1, 0)
>>> for city in metro_data:
... print(cc_name(city))
...
('JP', 'Tokyo')
('IN', 'Delhi NCR')
('MX', 'Mexico City')
('US', 'New York-Newark')
('BR', 'Sao Paulo')
itemgetter 使用 [] 运算符,因此它不仅支持序列,还支持映射和任何实现 _getitem_ 方法的类。
dis 模块为反汇编 Python 函数字节码提供了简单的方式
print(zip(range(3), 'ABC')) # ➊ zip 函数返回一个生成器,按需生成元组。
#
print(list(zip(range(3), 'ABC'))) # ➋ 为了输出,构建一个列表;通常,我们会迭代生成器。
# [(0, 'A'), (1, 'B'), (2, 'C')]
print(list(zip(range(3), 'ABC', [0.0, 1.1, 2.2, 3.3]))) # ➌ zip 有个奇怪的特性:当一个可迭代对象耗尽后,它不发出警告就停止。
# [(0, 'A', 0.0), (1, 'B', 1.1), (2, 'C', 2.2)]
from itertools import zip_longest
# ➍ itertools.zip_longest 函数的行为有所不同:使用可选的fillvalue(默认值为 None)填充缺失的值,因此可以继续产出,直到最长的可迭代对象耗尽。
print(list(zip_longest(range(3), 'ABC', [0.0, 1.1, 2.2, 3.3], fillvalue=-1)))
# [(0, 'A', 0.0), (1, 'B', 1.1), (2, 'C', 2.2), (-1, -1, 3.3)]
def __delattr__(self, *args, **kwargs):
def __dir__(self):
def __eq__(self, *args, **kwargs):
def __format__(self, *args, **kwargs):
def __getattribute__(self, *args, **kwargs):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __hash__(self, *args, **kwargs):
def __init_subclass__(self, *args, **kwargs):
def __init__(self):
def __le__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __new__(cls, *more):
def __ne__(self, *args, **kwargs):
def __reduce_ex__(self, *args, **kwargs):
def __reduce__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __setattr__(self, *args, **kwargs):
def __sizeof__(self):
def __str__(self, *args, **kwargs):
def __subclasshook__(cls, subclass):
def bit_length(self):
def conjugate(self, *args, **kwargs):
def from_bytes(cls, bytes, byteorder, *args, **kwargs):
def to_bytes(self, length, byteorder, *args, **kwargs):
def __abs__(self, *args, **kwargs):
def __add__(self, *args, **kwargs):
def __and__(self, *args, **kwargs):
def __bool__(self, *args, **kwargs):
def __ceil__(self, *args, **kwargs):
def __divmod__(self, *args, **kwargs):
def __eq__(self, *args, **kwargs):
def __float__(self, *args, **kwargs):
def __floordiv__(self, *args, **kwargs):
def __floor__(self, *args, **kwargs):
def __format__(self, *args, **kwargs):
def __getattribute__(self, *args, **kwargs):
def __getnewargs__(self, *args, **kwargs):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __hash__(self, *args, **kwargs):
def __index__(self, *args, **kwargs):
def __init__(self, x, base=10):
def __int__(self, *args, **kwargs):
def __invert__(self, *args, **kwargs):
def __le__(self, *args, **kwargs):
def __lshift__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __mod__(self, *args, **kwargs):
def __mul__(self, *args, **kwargs):
def __neg__(self, *args, **kwargs):
def __new__(*args, **kwargs):
def __ne__(self, *args, **kwargs):
def __or__(self, *args, **kwargs):
def __pos__(self, *args, **kwargs):
def __pow__(self, *args, **kwargs):
def __radd__(self, *args, **kwargs):
def __rand__(self, *args, **kwargs):
def __rand__(self, *args, **kwargs):
def __rdivmod__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __rfloordiv__(self, *args, **kwargs):
def __rlshift__(self, *args, **kwargs):
def __rmod__(self, *args, **kwargs):
def __rmul__(self, *args, **kwargs):
def __ror__(self, *args, **kwargs):
def __round__(self, *args, **kwargs):
def __rpow__(self, *args, **kwargs):
def __rrshift__(self, *args, **kwargs):
def __rshift__(self, *args, **kwargs):
def __rsub__(self, *args, **kwargs):
def __rtruediv__(self, *args, **kwargs):
def __rxor__(self, *args, **kwargs):
def __sizeof__(self, *args, **kwargs):
def __str__(self, *args, **kwargs):
def __sub__(self, *args, **kwargs):
def __truediv__(self, *args, **kwargs):
def __trunc__(self, *args, **kwargs):
def __xor__(self, *args, **kwargs):
def capitalize(self):
def casefold(self):
def center(self, width, fillchar=None):
def count(self, sub, start=None, end=None):
def encode(self, encoding='utf-8', errors='strict'):
def endswith(self, suffix, start=None, end=None):
def expandtabs(self, tabsize=8):
def find(self, sub, start=None, end=None):
def format(self, *args, **kwargs):
def format_map(self, mapping):
def index(self, sub, start=None, end=None):
def isalnum(self):
def isalpha(self):
def isdecimal(self):
def isdigit(self):
def isidentifier(self):
def islower(self):
def isnumeric(self):
def isprintable(self):
def isspace(self):
def istitle(self):
def isupper(self):
def join(self, iterable):
def ljust(self, width, fillchar=None):
def lower(self):
def lstrip(self, chars=None):
def maketrans(self, *args, **kwargs):
def partition(self, sep):
def replace(self, old, new, count=None):
def rfind(self, sub, start=None, end=None):
def rindex(self, sub, start=None, end=None):
def rjust(self, width, fillchar=None):
def rpartition(self, sep):
def rsplit(self, sep=None, maxsplit=-1):
def rstrip(self, chars=None):
def split(self, sep=None, maxsplit=-1):
def splitlines(self, keepends=None):
def startswith(self, prefix, start=None, end=None):
def strip(self, chars=None):
def swapcase(self):
def title(self):
def translate(self, table):
def upper(self):
def zfill(self, width):
def __add__(self, *args, **kwargs):
def __contains__(self, *args, **kwargs):
def __eq__(self, *args, **kwargs):
def __format__(self, format_spec):
def __getattribute__(self, *args, **kwargs):
def __getitem__(self, *args, **kwargs):
def __getnewargs__(self, *args, **kwargs):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __hash__(self, *args, **kwargs):
def __init__(self, value='', encoding=None, errors='strict'):
def __iter__(self, *args, **kwargs):
def __len__(self, *args, **kwargs):
def __le__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __mod__(self, *args, **kwargs):
def __mul__(self, *args, **kwargs):
def __new__(*args, **kwargs):
def __ne__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __rmod__(self, *args, **kwargs):
def __rmul__(self, *args, **kwargs):
def __sizeof__(self):
def __str__(self, *args, **kwargs):
def append(self, p_object):
def clear(self):
def copy(self):
def count(self, value):
def extend(self, iterable):
def index(self, value, start=None, stop=None):
def insert(self, index, p_object):
def pop(self, index=None):
def remove(self, value):
def reverse(self):
def sort(self, key=None, reverse=False):
def __add__(self, *args, **kwargs):
def __contains__(self, *args, **kwargs):
def __delitem__(self, *args, **kwargs):
def __eq__(self, *args, **kwargs):
def __getattribute__(self, *args, **kwargs):
def __getitem__(self, y):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __iadd__(self, *args, **kwargs):
def __imul__(self, *args, **kwargs):
def __init__(self, seq=()):
def __iter__(self, *args, **kwargs):
def __len__(self, *args, **kwargs):
def __le__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __mul__(self, *args, **kwargs):
def __new__(*args, **kwargs):
def __ne__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __reversed__(self):
def __rmul__(self, *args, **kwargs):
def __setitem__(self, *args, **kwargs):
def __sizeof__(self):
def clear(self):
def copy(self):
def fromkeys(*args, **kwargs):
def get(self, k, d=None):
def items(self):
def keys(self):
def pop(self, k, d=None):
def popitem(self):
def setdefault(self, k, d=None):
def update(self, E=None, **F):
def values(self):
def __contains__(self, *args, **kwargs):
def __delitem__(self, *args, **kwargs):
def __eq__(self, *args, **kwargs):
def __getattribute__(self, *args, **kwargs):
def __getitem__(self, y):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __init__(self, seq=None, **kwargs):
def __iter__(self, *args, **kwargs):
def __len__(self, *args, **kwargs):
def __le__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __new__(*args, **kwargs):
def __ne__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __setitem__(self, *args, **kwargs):
def __sizeof__(self):
def count(self, value):
def index(self, value, start=None, stop=None):
def __add__(self, *args, **kwargs):
def __contains__(self, *args, **kwargs):
def __eq__(self, *args, **kwargs):
def __getattribute__(self, *args, **kwargs):
def __getitem__(self, *args, **kwargs):
def __getnewargs__(self, *args, **kwargs):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __hash__(self, *args, **kwargs):
def __init__(self, seq=()):
def __iter__(self, *args, **kwargs):
def __len__(self, *args, **kwargs):
def __le__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __mul__(self, *args, **kwargs):
def __new__(*args, **kwargs):
def __ne__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __rmul__(self, *args, **kwargs):
def add(self, *args, **kwargs):
def clear(self, *args, **kwargs):
def copy(self, *args, **kwargs):
def difference(self, *args, **kwargs):
def difference_update(self, *args, **kwargs):
def discard(self, *args, **kwargs):
def intersection(self, *args, **kwargs):
def intersection_update(self, *args, **kwargs):
def isdisjoint(self, *args, **kwargs):
def issubset(self, *args, **kwargs):
def issuperset(self, *args, **kwargs):
def pop(self, *args, **kwargs):
def remove(self, *args, **kwargs):
def symmetric_difference(self, *args, **kwargs):
def symmetric_difference_update(self, *args, **kwargs):
def union(self, *args, **kwargs):
def update(self, *args, **kwargs):
def __and__(self, *args, **kwargs):
def __contains__(self, y):
def __eq__(self, *args, **kwargs):
def __getattribute__(self, *args, **kwargs):
def __ge__(self, *args, **kwargs):
def __gt__(self, *args, **kwargs):
def __iand__(self, *args, **kwargs):
def __init__(self, seq=()):
def __ior__(self, *args, **kwargs):
def __isub__(self, *args, **kwargs):
def __iter__(self, *args, **kwargs):
def __ixor__(self, *args, **kwargs):
def __len__(self, *args, **kwargs):
def __le__(self, *args, **kwargs):
def __lt__(self, *args, **kwargs):
def __new__(*args, **kwargs):
def __ne__(self, *args, **kwargs):
def __or__(self, *args, **kwargs):
def __rand__(self, *args, **kwargs):
def __reduce__(self, *args, **kwargs):
def __repr__(self, *args, **kwargs):
def __ror__(self, *args, **kwargs):
def __rsub__(self, *args, **kwargs):
def __rxor__(self, *args, **kwargs):
def __sizeof__(self):
def __sub__(self, *args, **kwargs):
def __xor__(self, *args, **kwargs):
def abs(*args, **kwargs):
def all(*args, **kwargs):
def any(*args, **kwargs):
def ascii(*args, **kwargs):
def bin(*args, **kwargs):
def callable(i_e_, some_kind_of_function):
def chr(*args, **kwargs):
def compile(*args, **kwargs):
def copyright(*args, **kwargs):
def credits(*args, **kwargs):
def delattr(x, y):
def dir(p_object=None):
def divmod(x, y):
def eval(*args, **kwargs):
def exec(*args, **kwargs):
def exit(*args, **kwargs):
def format(*args, **kwargs):
def getattr(object, name, default=None):
def globals(*args, **kwargs):
def hasattr(*args, **kwargs):
def hash(*args, **kwargs):
def help():
def hex(*args, **kwargs):
def id(*args, **kwargs):
def input(*args, **kwargs):
def isinstance(x, A_tuple):
def issubclass(x, A_tuple):
def iter(source, sentinel=None):
def len(*args, **kwargs):
def license(*args, **kwargs):
def locals(*args, **kwargs):
def max(*args, key=None):
def min(*args, key=None):
def next(iterator, default=None):
def oct(*args, **kwargs):
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True):
def ord(*args, **kwargs):
def pow(*args, **kwargs):
def print(self, *args, sep=' ', end='\n', file=None):
def quit(*args, **kwargs):
def repr(obj):
def round(number, ndigits=None):
def setattr(x, y, v):
def sorted(*args, **kwargs):
def sum(*args, **kwargs):
def vars(p_object=None):
class object:
class BaseException(object):
class Exception(BaseException):
class ArithmeticError(Exception):
class AssertionError(Exception):
class AttributeError(Exception):
class WindowsError(Exception):
class BlockingIOError(OSError):
class int(object):
class bool(int):
class ConnectionError(OSError):
class BrokenPipeError(ConnectionError):
class BufferError(Exception):
class bytearray(object):
class bytes(object):
class Warning(Exception):
class BytesWarning(Warning):
class ChildProcessError(OSError):
class classmethod(object):
class complex(object):
class ConnectionAbortedError(ConnectionError):
class ConnectionRefusedError(ConnectionError):
class ConnectionResetError(ConnectionError):
class DeprecationWarning(Warning):
class dict(object):
class enumerate(object):
class EOFError(Exception):
class FileExistsError(OSError):
class FileNotFoundError(OSError):
class filter(object):
class float(object):
class FloatingPointError(ArithmeticError):
class frozenset(object):
class FutureWarning(Warning):
class GeneratorExit(BaseException):
class ImportError(Exception):
class ImportWarning(Warning):
class SyntaxError(Exception):
class IndentationError(SyntaxError):
class LookupError(Exception):
class IndexError(LookupError):
class InterruptedError(OSError):
class IsADirectoryError(OSError):
class KeyboardInterrupt(BaseException):
class KeyError(LookupError):
class list(object):
class map(object):
class MemoryError(Exception):
class memoryview(object):
class ModuleNotFoundError(ImportError):
class NameError(Exception):
class NotADirectoryError(OSError):
class RuntimeError(Exception):
class NotImplementedError(RuntimeError):
class OverflowError(ArithmeticError):
class PendingDeprecationWarning(Warning):
class PermissionError(OSError):
class ProcessLookupError(OSError):
class property(object):
class range(object):
class RecursionError(RuntimeError):
class ReferenceError(Exception):
class ResourceWarning(Warning):
class reversed(object):
class RuntimeWarning(Warning):
class set(object):
class slice(object):
class staticmethod(object):
class StopAsyncIteration(Exception):
class StopIteration(Exception):
class str(object):
class super(object):
class SyntaxWarning(Warning):
class SystemError(Exception):
class SystemExit(BaseException):
class TabError(IndentationError):
class TimeoutError(OSError):
class tuple(object):
class type(object):
class TypeError(Exception):
class UnboundLocalError(NameError):
class ValueError(Exception):
class UnicodeError(ValueError):
class UnicodeDecodeError(UnicodeError):
class UnicodeEncodeError(UnicodeError):
class UnicodeTranslateError(UnicodeError):
class UnicodeWarning(Warning):
class UserWarning(Warning):
class ZeroDivisionError(ArithmeticError):
class zip(object):
class deque(object):
class defaultdict(dict):
def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None):
class UserDict(MutableMapping):
class UserList(MutableSequence):
class UserString(Sequence):
class Counter(dict):
class OrderedDict(dict):
class ChainMap(MutableMapping):
def update_wrapper(wrapper,
wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
def wraps(wrapped,
assigned = WRAPPER_ASSIGNMENTS,
updated = WRAPPER_UPDATES):
def total_ordering(cls):
def cmp_to_key(mycmp):
def cmp_to_key(*args, **kwargs):
def lru_cache(maxsize=128, typed=False):
def reduce(function, sequence, initial=None):
class partial:
class partialmethod(object):
def singledispatch(func):
class accumulate(object):
class chain(object):
class combinations(object):
class combinations_with_replacement(object):
class compress(object):
class count(object):
class cycle(object):
class dropwhile(object):
class filterfalse(object):
class groupby(object):
class islice(object):
class permutations(object):
class product(object):
class repeat(object):
class starmap(object):
class takewhile(object):
class zip_longest(object):
一般用于特殊方法的命名,用来实现对象的一些行为或者功能。
用于对象的数据封装,以此命名的属性或者方法为类的私有属性或者私有方法。
Python 管理这些名称,它用于避免名称与子类定义的名称冲突。
所有以双下划线开头的名称__name都会自动变为"_类名__name"的新名称。
一般用于模块中的"私有"定义的命名。
名称前的单个下划线用于指定程序员将名称视为“私有”。这可以视为一种约定,方便阅读代码的人知道以 _ 开头的名称供内部使用。
带有下划线的名称(例如 _spam)应被视为 API 的非公开部分(无论是函数、方法还是数据成员)。
from module import * 语句用于加载模块中的所有名称,要控制导入的名称,一种方法是定义列表__all__,只有在__all__中的名称才能通过*导入;
另一种方法就是以单下划线开头命名定义了,这种定义不会被*导入。
如果是模块的私有类,还可能有一个前缀下划线(主要目的是防止可能与祖先类的类成员发生名称冲突。)
_ 用作一次性的名称。这为了让阅读代码的人知道,这里分配了某个名称,但是不打算使用
for _ in range(10)
名称后面的单个下划线用于避免名称遮盖另一个名称,当然是惯例。例如,如果你想命名某种格式,为了避免掩盖 Python 的内置格式,你可以将其命名为format_。
一般来说,要使用某个类的方法,需要先实例化一个对象再调用方法。
而使用@staticmethod或@classmethod,就可以不需要实例化,直接通过类名就可以实现调用。
使用:**直接类名.方法名()**来调用。这有利于组织代码,把某些应该属于某个类的函数给放到那个类里去,同时有利于命名空间的整洁。
@staticmethod不需要表示自身对象的self和自身类的cls参数(这两个参数都不需要添加),就跟使用函数一样。使用:直接类名.属性名或直接类名.方法名。直接类名,也可以直接类名( )
#直接定义一个test()函数
def test():
print "i am a normal method!"
#定义一个类,其中包括一个类方法,采用@staticmethod修饰
class T:
@staticmethod
def static_test(): #没有self参数
print "i am a static method!"
if __name__ == "__main__":
test() # 1
T.static_test() # 2
T().static_test() # 3
output:
i am a normal method!
i am a static method!
i am a static method!
@classmethod也不需要self参数,但第一个参数需要是表示自身类的cls参数。使用:直接类名.属性名或直接类名.方法名,直接类名,也可以直接类名( )
class T:
@classmethod
def class_test(cls): #必须有cls参数 #这里第一个参数是cls, 表示调用当前的类名
print "i am a class method"
if __name__ == "__main__":
T.class_test()
T().class_test()
output:
i am a class method
i am a class method
用访问类属性的方式,直接调用类方法
import math
class Circle:
def __init__(self,radius): #圆的半径radius
self.radius=radius
@property
def area(self):
return math.pi * self.radius**2 #计算面积
@property
def perimeter(self):
return 2*math.pi*self.radius #计算周长
c=Circle(10)
print(c.radius)
print(c.area) #可以向访问数据属性一样去访问area,会触发一个函数的执行,动态计算出一个值
print(c.perimeter) #同上
'''
输出结果:
314.1592653589793
62.83185307179586
'''
设置属性值:
@property
装饰的方法是获取属性值的方法,被装饰方法的名字会被用做属性名。@属性名.setter
装饰的方法是设置属性值的方法。@属性名.deleter
装饰的方法是删除属性值的方法。class Student:
def __init__(self):
self._score = ''
@property
def score(self):
return self._score
@score.setter
def score(self, value):
if not isinstance(value, int):
raise ValueError('分数必须是数字')
if value > 100 or value < 0:
raise ValueError('分数不符实际')
self._score = value
@score.deleter
def score(self):
del self._score
s = Student()
s.score = 100
print(s.score) # 100
s.score = 150
print(s.score) # 报错
del s.score
print(s.score) # 报错
面向对象的封装有三种方式:
class Foo:
def __init__(self, val):
self.__NAME = val # 将所有的数据属性都隐藏起来
@property
def name(self):
return self.__NAME # obj.name访问的是self.__NAME(这也是真实值的存放位置)
@name.setter
def name(self, value):
if not isinstance(value, str): # 在设定值之前进行类型检查
raise TypeError('%s must be str' % value)
self.__NAME = value # 通过类型检查后,将值value存放到真实的位置self.__NAME
@name.deleter
def name(self):
raise TypeError('Can not delete')
f = Foo('tom')
print(f.name)
f.name = 10 # 抛出异常'TypeError: 10 must be str'
# del f.name # 抛出异常'TypeError: Can not delete'