2013-02-26 74 views
3

因爲一切都是Python中的對象(即使是函數),是否有可能從函數類實際擴展?例如,我可以使用字符串類型執行以下操作。有什麼辦法可以在功能類型上做類似的事情嗎?是否可以從Python中的內置函數類擴展?

class Foo(str): 
    def appendFoo(self): 
     return self+'foo' 

foo = Foo('test') 
print foo 
>>> test 
print foo.upper() 
>>> TEST 
print foo.appendFoo() 
>>> testfoo 
+0

請問您是否可以說明您的意思,可能還會添加示例? – Volatility 2013-02-26 05:55:31

+0

@Volatility我只是在探索語言,想知道是否有可能。謝謝。 – 2013-02-26 06:01:51

+1

相關:http://stackoverflow.com/questions/10061752/which-classes-cannot-be-subclassed – 2013-02-26 06:05:03

回答

1

不,我希望。你被困在函數中。

>>> def f(): pass 
... 
>>> type(f) 
<type 'function'> 
>>> function 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
NameError: name 'function' is not defined 
>>> function = type(f) 
>>> class MyFunc(function): 
...  pass 
... 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: Error when calling the metaclass bases 
    type 'function' is not an acceptable base type 
>>> type('MyFunc', (function,), {}) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
TypeError: type 'function' is not an acceptable base type 
+0

只需使用'types.FunctionType'就可以減少混亂 – 2013-02-26 06:09:05