Python多个"self"引用



我可能是疯了,但我想知道下面的方法是否可行,或者做下面的事情有什么更好的方法。

假设我有一个类:

class Alpha:
def __getattr__(self, label):
# Set the name / label
self.label = label
# Return the self instance
return self
def a_function(self):
print(f'Label: {self.label}')

我可以这样调用类Alpha:

a = Alpha()
# Prints `Label: foo`
a.foo.a_function()

现在假设我想创建一个包装器类:

class Beta:
def __getattr__(self, label):
# Set the name / label
self.label = label
# Return the self instance
return self
def b_function(self):
a = Alpha()
# Does not work
# But want to make a call like this
a.self.label.a_function()

Beta是一种包装类,我将调用Beta,如果您愿意,它反过来用相同的label调用Alpha:

b = Beta()
# Want to call `a_function` from a `b` object with `__getattr__`
# Expect to print `Label: bar`
b.bar.b_function()

使用继承,您可以让子类Beta()访问(或调用)父类Alpha()上定义的函数a_function()

class Alpha():
def __getattr__(self, label):
# Set the name / label
self.label = label
# Return the self instance
return self
def a_function(self):
print(f'Label: {self.label}')

class Beta(Alpha):
pass

:

a = Alpha()
a.bar.a_function()
# prints 'Label: bar'
b = Beta()
b.foo.a_function()
# prints 'Label: foo'

最新更新