How to inherit the properties of a member variable into the host class?
Imagine the following code:
class X(object):
def geta(self):
return self.__a
def seta(self, v):
self.__a = v
def __init__(self, a=0):
self.__a = a
a = property(geta, seta)
class Y(object):
def __init__(self, v):
self.X = X(v)
# !!! Here, not sure how to do it
a = X.a
x = X(12)
print x.a
x.a = 2
print x.a
print "-" * 79
y = Y(2)
print y.a
Essentially, what I want is to have class Y
inherit class X
's properties. So that Y.a
will actually go to Y.X.a
. So if I say: y = Y(2)
and then y.a = 2
it should be as if I did y.X.a = 开发者_运维知识库2
.
Is this possible?
Add this to Y:
def __getattr__(self, attr):
return getattr(self.X, attr)
Now all unresolved attribute references to a Y instance will forward to its contained X.
Properties are inherited like any other attribute... if you actually inherit from the class. What's wrong with that?
class Y(X): pass
精彩评论