首页 > python如何(查看类的所有实例),且(不通过某实例名称)调用(该实例)的方法

python如何(查看类的所有实例),且(不通过某实例名称)调用(该实例)的方法

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()。


问题描述有点绕, 不知道是不是我理解的样子: 其实是为了把某个对象实例化的时候,记录下来。就比如你的a对象就是专职做这个事情的。如果我理解的对的话,可以这样实现,比如计数:
借用一个长度为1的list对象存储 log. 不知道是不是你想要的意思--不是的话,我就忽略答案了。


是这个意思吧?

class A(object):
    obj = [0]

    def __init__(self, name=""):
        if name == "a":
            self. obj[0] = self
            self.obj[0].var = 0
        self.name = name

    def increase(self):
        if isinstance(self.obj[0], A):
            self.obj[0]._increase()

    def _increase(self):
        self.obj[0].var += 1
        print 'it is the object:', self.obj[0].name
        print 'the val:', self.obj[0].var

执行效果如下:


In [2]: a = A('a')

In [3]: a.increase()
it is the object: a
the val: 1

In [4]: b = A()

In [5]: b.increase()
it is the object: a
the val: 2

In [6]: c = A()

In [7]: c.increase()
it is the object: a
the val: 3
【热门文章】
【热门文章】