class Animal: def __init__(self, name): self.name = name def eat(self): print('%s吃飯' % self.name) class Dog(Animal): pass dog = Dog('小花狗') print(hasattr(dog, 'eat')) print(hasattr(dog, 'eater')) print(hasattr(dog, 'name')) out: True False True
class Animal: def __init__(self, name): self.name = name def eat(self): print('%s吃飯' % self.name) class Dog(Animal): pass dog = Dog('小花狗') print(getattr(dog, 'name')) print(getattr(dog, 'eat')) func = getattr(dog, 'eat') func() # 不指定default會報錯 print(getattr(dog, 'food', '不存在的屬性')) out: 小花狗 <bound method Animal.eat of <__main__.Dog object at 0x00000217FD770AC8>> 小花狗吃飯 不存在的屬性
當要反射本身模塊中的變量(或函數,能夠藉助sys模塊和__name__實現。使用變量__name__是由於在本身模塊運行時,__name__就是__main__,函數
而若是該模塊是被到入模塊時,確保反射的仍是此模塊的變量(或函數)。ui
import sys year = 2019 args = input('>>>') print(getattr(sys.modules[__name__],args))
def setattr(x, y, v): # real signature unknown; restored from __doc__ """ Sets the named attribute on the given object to the specified value. setattr(x, 'y', v) is equivalent to ``x.y = v'' """ pass
class Animal: def __init__(self, name): self.name = name def eat(self): print('%s吃飯' % self.name) class Dog(Animal): pass dog = Dog('小花狗') setattr(dog, 'food', '骨頭') setattr(dog, 'name', '王二狗') print(dog.__dict__) ''' 打印結果 {'name': '王二狗', 'food': '骨頭'} '''
def delattr(x, y): # real signature unknown; restored from __doc__ """ Deletes the named attribute from the given object. delattr(x, 'y') is equivalent to ``del x.y'' """ pass
class Animal: def __init__(self, name): self.name = name def eat(self): print('%s吃飯' % self.name) class Dog(Animal): pass dog = Dog('小花狗') setattr(dog, 'age', 2) setattr(dog, 'food', '骨頭') print(dog.__dict__) delattr(dog, 'name') print(dog.__dict__) ''' 打印結果 {'name': '小花狗', 'age': 2, 'food': '骨頭'} {'age': 2, 'food': '骨頭'} '''