Python中是否有一种方法可以获得对调用方法的对象的引用?
如果是的话,它是否有可能,即使是嵌套的方式?
my_class.py:
from modules import math_ops
class A():
def __init__(self):
self.math_ops = math_ops.B()
self.number = 1模块/数学_ops.py:
class B():
def add_1():
where_to_add = # Get instance of A() object
where_to_add.number += 1若要执行此操作,请执行:
>>> a = A()
>>> a.math_ops.add_1()得到这个:
>>> a.number
2我之所以问这个问题,是因为我对编写一个静态方法感兴趣,它与调用对象的对象一起工作,但希望避免使用对象作为参数,因为调用像my_object.prop.static_method()这样的方法要好得多,而不是my_object.prop.static_method(my_object)。
发布于 2018-11-16 13:04:15
如果您从未计划过在math_ops之外重新分配A,这是相当简单的。
from modules import math_ops
class A():
def __init__():
self.math_ops = math_ops.B(self)
self.number = 1模块/数学_ops.py:
class B():
def __init__(self, creator):
self.creator = creator
def add_1():
creator.number += 1如果您浏览了第一行,我将再次提到它,因为B跟踪的是对象的创建者,而不是调用者,因此下面的结果将产生意外的结果。
a1 = A()
a2 = A()
a1.math_ops = a2.math_ops
a1.math_ops.add_1() # a2 is updated如果这看起来像是你想做的事情,那么答案就有点复杂了。以下是我的尝试:
from modules import math_ops
class A():
def __init__(self):
self._math_ops = math_ops.B(self)
self.number = 1
@property
def math_ops(self):
self._math_ops.set_caller(self)
return self._math_ops
@math_ops.setter
def math_ops(self, new_math_ops):
self._math_ops = new_math_ops模块/数学_ops.py:
class B():
def __init__(self, caller):
self.caller = caller
def set_caller(self, caller):
self.caller = caller
def add_1(self):
self.caller.number += 1发布于 2018-11-16 11:07:14
class A():
number = 1
class B():
def add_1():
where_to_add = A
where_to_add.number += 1
B.add_1()
print(A.number)
B.add_1()
print(A.number)
B.add_1()
print(A.number)https://stackoverflow.com/questions/53336487
复制相似问题