#getattr函数
#getattr() 函数用于返回一个对象属性值。
class Test(object):
head = 1
def __init__(self,name):
self.name = name
@classmethod
def func(cls):
cls.num = 666
num1 = 888
t = Test('xiaowang')
result = getattr(t,"head")
print(result) #结果:1
bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
chr() 用一个范围在 range(256)内的(就是0~255)整数作参数,返回一个对应的字符。
# callable() 函数用于检查一个对象是否是可调用的。如果返回
# True,object 仍然可能调用失败;但如果返回 False,调用对象 object 绝对不会成功。
# 对于函数、方法、lambda 函式、 类以及实现了 __call__ 方法的类实例, 它都返回 True。
class B:
def __call__(self):
return 0
print(callable(B)) #True
#classmethod 修饰符对应的函数不需要实例化
# 不需要 self 参数,但第一个参数需要是表示自身类
# 的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
class A(object):
bar = 1
def func1(self):
print('foo')
@classmethod
def func2(cls):
cls.num = 666 #定义一个类变量
print('func2')
print(cls.bar)
print(cls.num)
cls().func1() # 调用 foo 方法
A.func2() # 不需要实例化
# delattr 函数用于删除属性。
# delattr(x, 'foobar') 相等于 del x.foobar。
class Test:
x = 10
y = -5
z = 0
t = Test()
print('x = ', t.x)
print('y = ', t.y)
print('z = ', t.z)
delattr(Test, 'z')
print('--删除 z 属性后--')
print('x = ', t.x)
print('y = ', t.y)
# 触发错误
print('z = ', t.z)
# eval() 函数用来执行一个字符串表达式,并返回表达式的值。
n=81
print(eval("n + 4"))
str="{'name':'xiaowang'}"
result = eval(str)
print(result,type(result)) #结果:{'name': 'xiaowang'} <class 'dict'>
#cmp(x,y) 函数用于比较2个对象,如果 x < y 返回 -1,
#如果 x == y 返回 0, 如果 x > y 返回 1。
import operator
a = 5
b = 3
print(operator.lt(a, b))#False
print(operator.le(a, b))#False
print(operator.eq(a, b))#False
print(operator.ne(a, b))#True
print(operator.ge(a, b))#True
print(operator.gt(a, b))#True
print(operator.__lt__(a, b))#False
print(operator.__le__(a, b))#False
print(operator.__eq__(a, b))#False
print(operator.__ne__(a, b))#True
print(operator.__ge__(a, b))#True
print(operator.__gt__(a, b))#True
#compile() 函数将一个字符串编译为字节代码。
str = "for i in range(0,10): print(i)"
c = compile(str,'','exec')
exec(c) #结果:0-9
str = "3 * 4 + 5"
a = compile(str,'','eval')
print(eval(a)) #结果:17