为了添加一个层级,curves
需要是一个实际的对象,是的。有以下foo.curves.plot()
和之间没有差异:
c = foo.curves
c.plot()
所以foo.curves
需要是具有plot
方法的对象。
此外,由于方法在curves
对象上调用,该方法将绑定到该对象。所以除非你这样设置,否则curves
对象将无法访问你的实际类。
你可以通过实例在curves
构造,但:
class Curves (object):
def __init__ (self, parent):
self.parent = parent
def plot (self):
self.parent._plot()
class MyClass (object):
def __init__ (self):
self.curves = Curves(self)
def _plot (self):
print('Actual plot implementation')
然后你可以使用它作为foo.curves.plot()
:
>>> foo = MyClass()
>>> foo.curves.plot()
Actual plot implementation
你也该使用自动化有点descriptor为curves
。例如,这是一个可能的解决方案:
class Accessor (object):
def __init__ (self, prefix = ''):
self.prefix = prefix
def __get__ (self, instance, owner):
return AccessorDelegate(instance, self.prefix)
class AccessorDelegate (object):
def __init__ (self, instance, prefix):
self.instance = instance
self.prefix = prefix
def __getattr__ (self, name):
return getattr(self.instance, self.prefix + name)
的好处是明显的,你只需要那些定义一个时间,然后他们会为您的所有类的工作。你会在你的课堂上使用这样的:
class MyClass (object):
curves = Accessor('_curves_')
def _curves_plot(self):
print('Implementation of curves.plot')
像上面完全相同:
>>> foo = MyClass()
>>> foo.curves.plot()
Implementation of curves.plot
如果你想调用'instance_of_my_class.curves.plot()'它必须是一个对象,或至少有一些可设置的属性。目前,您的'plot()'只在调用'curves()'函数的环境内定义。即''plot()'只在调用'curves()'时创建,并且只能在'curves()中访问'' – Eric
使用'curves'中的任何变量'plot',例如'plot'。 “自我”还是其他什么可能是你不在这个简短的例子中展示的?如果是这样,当称为“曲线”的“外部”时,这些变量的值应该是多少?如果没有,为什么首先在'curves'内定义它? –
@jojo类方法不会传递实例吗? – poke