class MyObject(object): def init(self): self.x = 9
def power(self): return self.x * self.x
obj = MyObject()
print(hasattr(obj, 'x')) # 有属性'x'吗? print(hasattr(obj, 'y')) # 有属性'y'吗? setattr(obj, 'y', 19) #设置一个属性‘y’吗? print(getattr(obj, 'y')) #获取属性‘y’ print(getattr(obj, 'z', 404)) #获取属性'z',如果不存在,返回默认值404
#也可以获得对象的方法: print(hasattr(obj, 'power')) #有属性'power'吗? print(getattr(obj, 'power')) #获取属性'power' fn = getattr(obj, 'power') #获取属性‘power’并赋值到变量fn print(fn)
Sign in to make a reply
GOGOGO-枼子
class MyObject(object): def init(self): self.x = 9
obj = MyObject()
print(hasattr(obj, 'x')) # 有属性'x'吗? print(hasattr(obj, 'y')) # 有属性'y'吗? setattr(obj, 'y', 19) #设置一个属性‘y’吗? print(getattr(obj, 'y')) #获取属性‘y’ print(getattr(obj, 'z', 404)) #获取属性'z',如果不存在,返回默认值404
#也可以获得对象的方法: print(hasattr(obj, 'power')) #有属性'power'吗? print(getattr(obj, 'power')) #获取属性'power' fn = getattr(obj, 'power') #获取属性‘power’并赋值到变量fn print(fn)