classmethod
classmethod是一个修饰符,表示该函数不需要实例化,没有self参数,但是第一个参数必须是表示自身类的cls,可以用来调用类的属性方法和实例化对象等。
测试代码:
class ClsWithClassmethod:
num = 99
def func1(self):
print("func1 called")
@classmethod
def func2(cls, obj):
print("func2 called")
print("num = ", cls.num)
cls.func3()
obj.func1()
@classmethod
def func3(cls):
print("func3 called")
def test_classmethod():
obj = ClsWithClassmethod()
ClsWithClassmethod.func2(obj)
test_classmethod()
输出结果:
func2 called
num = 99
func3 called
func1 called
cmp
cmp()函数在python3中已经被删除了,类似功能可以通过operator.lt()、operator.le()、operator.eq()、operator.ne()、operator.gt()、operator.ge()等实现。这里不再介绍了。
compile
compile()函数是将参数source指定的字符串源码编译为可执行代码或者是AST(Abstract Syntax Trees)对象。
函数定义:
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)
参数说明
- source: 可以是一个字符串、字节字符串或者AST对象
- filename:读取源码的文件,如果不是从文件读取直接传递一个可辨认的值,通常使用"<string>"
- mode:指定要编译的代码的类型:
- exec:如果source包含多条python语句
- eval:source只包含一条语句
- single:包含交互的单个语句
- flags和dont_inherit:如果两者使用缺省参数(也即两者都是零值),在调用本函数编译时,主要使用代码中指明的编译特征来对待;如果flags参数设置有值,而dont_inherit没有设置(即是零值),那么编译代码时,不仅源码的编译特征起作用,而且flags指明的特征也起作用,相当两者的并集;如果参数dont_inherit设置有值(即是非零值),编译语句时只有参数flags指明的编译特征值起作用,即是不使用源码里指明的特征。
- optimize:缺省值是-1,表示使用命令行参数-O中获取的优化等级为准;如果设置值为0(即是不用优化,__debug__是设置true),是没有优化;如果设置值为1,assert语句被删除,__debug__设置为false;如果设置值为2,除了设置值为1的功能之外,还会把代码里文档说明也删除掉,达到最佳优化结果。
测试代码:
def test_compile():
code_str = "a = 1\r\nb=2\r\nc = a + b\r\nprint('c = ', c)"
code = compile(code_str, "<string", "exec")
exec(code)
code = compile("", filename="./test_dir.py", mode="exec")
exec(code)
code_str = "3+4"
code = compile(code_str, "<string", "eval")
exec(code)
code = compile(code_str, "<string", "single")
exec(code)
test_compile()
测试结果:
c = 3
7
comlpex
complex()函数返回一个值为real + imag*1j的复数,或者将一个字符串或者数字转换为复数。如果第一个为字符串,则该字符串被作为复数来解释,并且忽略第二个参数。第二个参数永远不能是字符串。 每个参数可以是任何数字类型(包括复数)。如果忽略imag,则imag默认值为0,相当于int或者float的转换函数。如果两个参数都忽略则返回0j。
定义:
class complex([real[, imag]])
测试代码:
def test_complex():
a = complex(1)
print("a = ", a)
b = complex(1.0)
print("b = ", b)
c = complex(-1)
print("c = ", c)
d = complex("2")
print("d = ", d)
#e = complex("2", "3") #error:TypeError: complex() can't take second arg if first is a string
#print("e = ", e)
d = complex("2+4j")
print("d = ", d)
e = complex(4, 5)
print("e = ", e)
#f = complex("2 + 4j") # error: the string must not contain whitespace around the central + or - operator
#print("f = ", f)
测试结果:
a = (1+0j)
b = (1+0j)
c = (-1+0j)
d = (2+0j)
d = (2+4j)
e = (4+5j)
hasattr
hasattr(object, name)用来判定某个对象是否拥有名称为name的属性。有则返回True否则返回False。
测试代码:
def test_setattr():
obj = TestClass()
print("dir(obj)", dir(obj))
setattr(obj, "first", 20)
print("first", obj.first)
setattr(obj, "third", 50.9)
print("dir(obj)", dir(obj))
test_setattr()
测试结果:
has attribute first? True
has attribute third? False
setattr
setattr()函数用来为一个对象设置属性值。该属性可以是已存在的也可以是没有的属性。参数是一个对象,一个string,一个任意值。 setattr(x, ‘foobar’, 123) 与 x.foobar = 123功能相同。
函数定义:
setattr(object, name, value)
测试代码:
def test_setattr():
obj = TestClass()
print("dir(obj)", dir(obj))
setattr(obj, "first", 20)
print("first", obj.first)
setattr(obj, "third", 50.9)
print("dir(obj)", dir(obj))
test_setattr()
测试输出:
dir(obj) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first', 'second']
first 20
dir(obj) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first', 'second', 'third']
getattr
getattr()函数用来获取对象的属性值。与setattr()函数功能对应。name必须是一个string。如果name是对象存在的属性则返回属性值。如果该属性不存在时,如果提供default值则返回default,否则抛出AttributeError 异常。getattr(x, ‘foobar’) 功能与 x.foobar相同。
函数定义:
getattr(object, name[, default])
测试代码:
def test_getattr():
obj = TestClass()
print("dir(obj)", dir(obj))
a = getattr(obj, "first")
print("a", a)
b = getattr(obj, "third", "100")
print("b", b)
#b = getattr(obj, "third") # error: AttributeError: 'TestClass' object has no attribute 'third'
#print("b", b)
测试输出:
dir(obj) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first', 'second']
a 10
b 100
delattr
delattr()函数用来删除一个对象的属性。参数是一个object和一个string。string必须是object的属性名。delattr(x, ‘foobar’)与del x.foobar效果是相同的。
函数定义:
delattr(object, name)
测试代码:
def test_delattr():
obj = TestClass()
print("dir(obj)", dir(obj))
delattr(obj, "first")
print("dir(obj)", dir(obj))
#delattr(obj, "third") # error: AttributeError: third
#print("dir(obj)", dir(obj))
test_delattr()
测试输出:
dir(obj) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'first', 'second']
dir(obj) ['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'second']
dict
dict()函数用于创建一个字典。
定义:
class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
测试代码:
def test_dict():
d1 = dict(a="1", b=2, c="string")
print("d1: ", d1)
d2 = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
print("d2: ", d2)
d3 = dict([('one', 1), ('two', 2), ('three', 3)])
print("d3: ", d3)
test_dict()
测试输出:
d1: {'a': '1', 'b': 2, 'c': 'string'}
d2: {'one': 1, 'two': 2, 'three': 3}
d3: {'one': 1, 'two': 2, 'three': 3}
divmod
divmod(a, b)函数返回两个值的商和余数的元组。
测试代码:
def test_divmod():
a = divmod(7, 3)
print("a: ", a)
b = divmod(7.5, 3.1)
print("b: ", b)
#c = divmod(3+4j, 7+9j) #error: TypeError: can't take floor or mod of complex number.
#print("c: ", c)
d = divmod(-7.5, 3.1)
print("d: ", d)
e = divmod(7.5, -3.1)
print("e: ", e)
test_divmod()
测试输出:
a: (2, 1)
b: (2.0, 1.2999999999999998)
d: (-3.0, 1.8000000000000003)
e: (-3.0, -1.8000000000000003)
enumerate
enumerate(iterable, start=0)函数返回一个枚举对象,同时列出数据和数据下标。iterable 必须是序列、迭代器或其他支持迭代的对象(如列表、元组或字符串)。
测试代码:
def test_enumerate():
enimal = ["dog", "cat", "pig", "bird"]
aa = enumerate(enimal)
print("aa: ", list(aa))
bb = enumerate(enimal, start=2)
print("bb: ", list(bb))
test_enumerate()
测试输出:
aa: [(0, 'dog'), (1, 'cat'), (2, 'pig'), (3, 'bird')]
bb: [(2, 'dog'), (3, 'cat'), (4, 'pig'), (5, 'bird')]