我需要一个物体来做任何事情

时间:2011-10-26 17:55:37

标签: python

或者至少,假装做任何事情。

>>> 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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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