2016-07-29 29 views
0

我有一个班的形式为:子功能没有对象引用declation

class MyClass(object): 
    def curves(self): 
    def plot(self): 
     plot a graph 
     return something 
    return a pd.DataFrame 

我想要做的是确定的东西,我可以instance_of_my_class.curves.plot()

我需要定义曲线作为来电反对使这成为可能?我正在寻找最短的方法来完成它,因为这只是语法糖。

谢谢。

+1

如果你想调用'instance_of_my_class.curves.plot()'它必须是一个对象,或至少有一些可设置的属性。目前,您的'plot()'只在调用'curves()'函数的环境内定义。即''plot()'只在调用'curves()'时创建,并且只能在'curves()中访问'' – Eric

+0

使用'curves'中的任何变量'plot',例如'plot'。 “自我”还是其他什么可能是你不在这个简短的例子中展示的?如果是这样,当称为“曲线”的“外部”时,这些变量的值应该是多少?如果没有,为什么首先在'curves'内定义它? –

+0

@jojo类方法不会传递实例吗? – poke

回答

0

为了添加一个层级,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 

你也该使用自动化有点descriptorcurves。例如,这是一个可能的解决方案:

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 
相关问题