爲了添加一個層級,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