>>> x =1>>>eval("x+1")2>>>eval("print('hello')")
hello
>>> y ='{"a":"1","b":[1,2,3]}'>>>eval(y){'a':'1','b':[1,2,3]}>>>eval("a=1+2")
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
File "<string>", line 1
a=1+2^
SyntaxError: invalid syntax
exec(object[, globals[, locals]])
>>> a =1>>> b =2>>>exec("x=a+1\ny=a+b")>>> x
2>>> y
3>>>exec("print(1);print(2)")12
实例属性操作函数
classMyClass:
a =1
b =2def__init__(self):
self.t =1defsay_hello(self):print("hello")
myclass = MyClass()
getattr(object, name[, default])
>>>getattr(myclass,"a")1>>>getattr(myclass,"c",100)100>>>getattr(myclass,"c")
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
AttributeError:'MyClass'object has no attribute 'c'>>>getattr(myclass,"say_hello")()
hello
>>>getattr(myclass,"say_hi",lambda:print("function no exists!"))()
function no exists!
>>>getattr(myclass,"say_hi")
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
AttributeError:'MyClass'object has no attribute 'say_hi'
>>>getattr(myclass,"t")1>>>delattr(myclass,"t")>>>getattr(myclass,"t")
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
AttributeError:'MyClass'object has no attribute 't'>>>delattr(myclass,"say_hello")
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
AttributeError: say_hello
>>>del myclass.say_hello
Traceback (most recent call last):
File "<stdin>", line 1,in<module>
AttributeError: say_hello
统计函数
min(iterable, *[, key, default])
>>>min([1,2,3])1>>>min([{"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100}],key=lambda x: x['score']){'name':'a','score':80}>>> a =[]>>> t =["iterable is empty!"]>>>min(a, key=lambda x:x['score'], default=t)['iterable is empty!']
>>>max([1,2,3])3>>>max([{"name":"a","score":80},{"name":"b","score":90},{"name":"c","score":100}],key=lambda x: x['score']){'name':'c','score':100}>>> a =[]>>> t =["iterable is empty!"]>>>max(a, key=lambda x:x['score'], default=t)['iterable is empty!']
>>>print('hello world!')
hello world!
>>>print('a','b','c')
a b c
>>>print('a','b','c',sep='')
abc
>>>print(1);print(2);print(3)123>>>print(1,end='');print(2,end='');print(3)123
import time
# 方法一withopen("text.txt","w")as f:for i inrange(1,3):print(i,file=f,flush=True)
time.sleep(1)#方法二withopen("text.txt","w")as f:
sys.stdout = f
for i inrange(1,3):print(i)
sys.stdout.flush()
time.sleep(1)
import time
withopen("text.txt","w")as f:for i inrange(1,3):print(i,file=f)
time.sleep(1)
类型函数
class bool([x])
class complex([real[, imag]])
class int([x])
class int(x, base=10)
class float([x])
class str(object='')
class str(object=b'', encoding='utf-8', errors='strict')