我需要“劫持”对对象实例成员的访问,而无需修改该类所有实例的行为。这可以实现吗?
考虑以下简化代码:
class S(object):
pass
Class C(object):
def __init__(self, s):
self.r = -1
self.s = s
# Add missing bits here?
s = S()
c = C(s)
print c.s.r # => should return the value of c.r, i.e. -1
c.s.r = -2 # should modify the value of c.r
s.r = -3 # ditto, should modify the value of c.r
请注意,S
的给定实例可以单独使用,也可以在多个C
对象之间共享,因此在S.__class__
上设置属性无效(或至少到目前为止,我都没想过要实现这个目标。
有什么想法吗?
答案 0 :(得分:0)
class S(object):
def __init__(self, r):
self.r = r
class C(object):
def __init__(self, s):
self.s = s
s = S(-1)
c = C(s)
print(c.s.r)
c.s.r = -2
print(c.s.r)
print(s.r)
s.r = -3
print(c.s.r)
print(s.r)
答案 1 :(得分:0)
图我将发布最终结果:
import weakref
class S(object):
def __init__(self):
self._r = -1
@property
def r(self):
try:
return self._c.r
except (AttributeError, ReferenceError):
return self._r
@r.setter
def r(self, value):
try:
self._c.r = value
except (AttributeError, ReferenceError):
self._r = value
class C(object):
def __init__(self, s):
self._r = -2
s._c = weakref.proxy(self)
self.s = s
@property
def r(self):
return self._r
@r.setter
def r(self, value):
self._r = value
def printRs(s, c):
print "s.r", s.r
if c:
print "c.r", c.r
print "c.s.r", c.s.r
s = S()
c = C(s)
printRs(s, c) # => -2 on all
c.r = 0
printRs(s, c) # => 0 on all
s.r = 1
printRs(s, c) # => 1 on all
c.s.r = 2
printRs(s, c) # => 2 on all
c = None
printRs(s, c) # => -1 on s.r