代码改变世界

pythontips(2):hasattr的用法

2017-06-01 09:42  很大很老实  阅读(560)  评论(0编辑  收藏  举报

  

class Xiaorui:
def __init__(self):
self.name = 'xiaorui'

def setName(self, name=''):
if name.strip():
self.name = name

def getName(self):
return self.name

def greet(self):
print("Hello, i'm %s" % self.name)

foo = Xiaorui()

if(hasattr(foo, 'setName')):
print(foo.setName())

if(hasattr(foo, 'getName')):
print(foo.getName())

if(hasattr(foo, 'setName')):
print(foo.setName('wcf'))

if(hasattr(foo, 'getName')):
print(foo.getName())