1.需要在其他运行时,调用父类中某个实例,因为该实例的方法会写入一个log.txt文件,如果重新调用的话,那么会新建一个新的文件,所以有什么办法,直接调用原实例的方法,并且不需要该实例的名称。
2.代码: # 用print和i++示意写log.txt
class Alpha(object):
def __init__(self):
self.var = 0
def increase(self):
self.var += 1
print self.var
>>>
a = A()
a.increase() # --> 1
a.increase() # --> 2
b.increase() # --> 1 重新写log 不对
??.increase() # -->3 如何不用a.crease()的形式 继续调用绑定到a的increase()方法?
有没有利用 getattr
或 *.__dict__
print getattr(a2, 'increase')
print getattr(Alpha, 'increase')
print a1.__dict__
print Alpha.__dict__
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'increase', 'var']
<bound method Alpha.increase of <main.Alpha object at 0x00000000027DF550>>
<bound method Alpha.increase of <main.Alpha object at 0x00000000027DF588>>
<unbound method Alpha.increase>
{'var': 3}
{'__module__': 'main', 'increase': <function increase at 0x00000000027C8AC8>, '__dict__': <attribute '__dict__' of 'Alpha' objects>, '__weakref__': <attribute '__weakref__' of 'Alpha' objects>, '__doc__': None, '__init__': <function __init__ at 0x00000000027C8A58>}
这些特性 获取class Alpha 实例方法的绑定地址如 <main.Alpha object at 0x00000000027DF550>>
然后调用a的方法 而不通过a.increase()。
是这个意思吧?
执行效果如下: