2011-10-26 22 views
-1

或者至少,假裝做任何事情。我需要一個物體來做任何事

>>> three = Three() 
>>> three.value() 
3 
>>> three.sqrt() 
3 
>>> three.close() 
3 
>>> three.someRandomFunctionWithMadeUpParameters("hello, world", math.PI, True) 
3 
>>> three.stopSayingThreeDamnIt() 
3 

是否有可能實現在Python 2.6 Three類?

+0

什麼是你想在這裏完成? –

+0

@RussellBorogove - 我想建立一個通用的管道錯誤對象,如[這裏]所述(http://stackoverflow.com/questions/7906187/enforcing-method-order-in-a-python-module/7906457#7906457 )。它會在現實生活中返回「自我」,而不是3.你的妻子不被命名爲Mimsy,是她嗎? – Malvolio

+0

在這種情況下,您可能更希望創建拋出原始返回值(或將其存儲在某處)的裝飾器,並返回「self」。 '__getattr__'只適用於不存在的東西,而使用'__getattribute__'可以完成這項工作,但仍然需要調用一個真正的函數來執行某些操作 - 使用裝飾器顯然更清晰。 – ThiefMaster

回答

2
class Three(object): 
    def __getattr__(self, name): 
     return lambda *args, **kw: 3 
+2

讓3一4然後你有一個最終的隨機號碼發生器! –

1
class MetaThree(type): 
    def __repr__(cls): 
     return '3' 
    def __getattr__(cls,key): 
     return Three 

class Three(object): 
    __metaclass__=MetaThree 
    def __init__(self,*args,**kwargs): 
     pass 
    def __call__(self): 
     return Three 
    def __getattr__(self,key): 
     return Three 
    def __repr__(self): 
     return '3' 

three=Three() 
print(three.value()) 
# 3 
print(three.someRandomFunc('hello')) 
# 3 
print(three.someRandomFunc) 
# 3 
print(three.someRandomFunc.foo.bar) 
# 3 
print(three()()()) 
# 3 
相關問題