2016-07-29 94 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 
相關問題