• 判断对象是否有这个名字的属性,有就返回True,没有就返回False。name必须为字符串
    1. hasaattr(object,name)
    • 1.例子:动态调用方法
    1. >>> if hasattr(p1, 'show'):
    2. >>> print(getattr(p1, 'show'))
    3. <bound method Point.show of <__main__.Point object at 0x0000014572376488>>
    • 动态增加方法
    1. >>> if not hasattr(Point, 'add'):
    2. >>> setattr(Point, 'add', lambda self, other: Point(self.x + other.x, self.y + other.y))
    3. >>> print(Point.add)
    4. <function <lambda> at 0x0000014572371558>
    5. >>> print(p1.add)
    6. <bound method <lambda> of <__main__.Point object at 0x0000014572376488>>
    7. >>> print(p1.add(p2))
    8. 14 and 26
    1. >>> if not hasattr(p1, 'sub'):
    2. >>> setattr(p1, 'sub', lambda self, other: Point(self.x - other.x, self.y - other.y))
    3. >>> print(p1.sub(p1, p2))
    4. -6 and 6
    5. >>> print(p1.__dict__)
    6. {'x': 4, 'y': 16, 'z': 10, 'sub': <function <lambda> at 0x0000014572381DC8>}
    7. >>> print(Point.__dict__)
    8. {'__module__': '__main__', '__init__': <function Point.__init__ at 0x00000145722E04C8>, '__str__': <function Point.__str__ at 0x00000145722E0318>, 'sho