# 静态:在定义阶段就确定类型
# 动态:在调用阶段才去确定类型
def func(obj):
if ‘x‘ not in obj.__dict__:
return
obj.x
func(10) # AttributeError: ‘int‘ object has no attribute ‘__dict__‘
print(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__‘, ‘age‘, ‘name‘, ‘say‘]
print(obj.__dict__[‘name‘]) # xxq
print(obj.__dict__[dir(obj)[-2]]) # xxq
print(hasattr(obj, ‘name‘)) # True
print(hasattr(obj, ‘x‘)) # False
print(getattr(obj, ‘name‘)) # xxq
print(getattr(obj, ‘x‘)) # AttributeError: ‘People‘ object has no attribute ‘x‘
print(getattr(obj, ‘name‘, ‘EGON‘)) # 修改名字为EGON
print(obj.name) # EGON
delattr(obj, ‘name‘)
print(obj.__dict__) # {‘age‘: 18}
res1 = getattr(obj, ‘say‘) # obj.say
res2 = getattr(People, ‘say‘) # People.say
print(res1) # <bound method People.say of <__main__.People object at 0x0167B0B8>>
print(res2) # <function People.say at 0x016783D0>
obj = 10
if hasattr(obj, ‘x‘):
print(getattr(obj, ‘x‘))
else:
print(‘找不到‘) # 找不到
print(getattr(obj, ‘x‘, None)) # None
print(getattr(People, ‘say‘, None)) # <function People.say at 0x01AC83D0>
if hasattr(obj, ‘x‘):
setattr(obj, ‘x‘, 1111111) # 10.x = 1111111
else:
print(‘找不到‘) # 找不到
class Ftp:
def upload(self):
print(‘正在上传‘)
def download(self):
print(‘正在下载‘)
def interactive(self):
method = input(‘>>>: ‘).strip() # method = ‘upload‘
if hasattr(self, method):
getattr(self, method)()
else:
print(‘该指令不存在!‘)
obj = Ftp()
obj.interactive()
原文:https://www.cnblogs.com/xuexianqi/p/12703295.html