Python从带有函数的类返回值

Python从带有函数的类返回值,python,function,class,Python,Function,Class,我想上这样的课: class Test: def __new__(cls): return 'test' def hi(self): print('hi') cl = Test() print(cl) cl.hi() 如您所见,我想创建一个在实例化时返回值的类,但仍然使用该类的函数,如下所示: class Test: def __new__(cls): return 'test' def hi(self):

我想上这样的课:

class Test:
    def __new__(cls):
        return 'test'

    def hi(self):
        print('hi')
cl = Test()
print(cl)
cl.hi()
如您所见,我想创建一个在实例化时返回值的类,但仍然使用该类的函数,如下所示:

class Test:
    def __new__(cls):
        return 'test'

    def hi(self):
        print('hi')
cl = Test()
print(cl)
cl.hi()
如果有人能帮助我,那就太好了

您想要这个:

class Test:

    def hi(self):
        print('hi')

    def __str__(self):
        return 'test'

cl = Test()
print(cl)
cl.hi()

方法
\uuu str\uuuu(self)
设置类作为字符串使用时的行为。

我想您正在寻找类似的内容

class Test:
    def __init__(self):
        pass

    def __str__(self):
        return 'test'

    def hi(self):
        print('hi')

特殊方法名称可能是您的好读物。 或者可能是这个。。。 类TestMe:

def __init__(self):
    print('init')

def hi(self):
    print('hi')

这不会更改MRO或类类型。它还需要一些工作

class MethodAdder:
    def __init__(self, obj):
        self._obj = obj

    def __str__(self):
        return str(self._obj)

    def __eq__(self, other):
        return self._obj == other

    def __ne__(self, other):
        return self._obj != other

    # ... and so on

    def __setattr__(self, key, value):
        try:
            if hasattr(object.__getattribute__(self, "_obj"), key):
                setattr(object.__getattribute__(self, "_obj"), key, value)
        except AttributeError:
            pass
        object.__setattr__(self, key, value)

    def __getattribute__(self, item):
        try:
            if hasattr(object.__getattribute__(self, "_obj"), item):
                return getattr(object.__getattribute__(self, "_obj"), item)
        except AttributeError:
            pass
        return object.__getattribute__(self, item)

    def hello(self):
        print("hello2")


v = MethodAdder("test")
print(v)
v.hello()
print(v.split("e"))


每个类在实例化时返回一个值(或引发异常…)。如果希望该值具有
Test
类的功能,则它必须是
Test
类型。在实例化
Test
时是否要打印字符串
'Test'
<示例中的code>cl可以是
Test
的实例,也可以是字符串
'Test'
,而不是两者都是(尽管您可以返回一个由两者组成的元组,并写入
cl,msg=Test()
,但要小心:除非
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>返回
Test的实例,
Test.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu初始化
将不会被调用。如果返回“Test”,则返回的是字符串而不是对象。您可以使用
\uuuuuuuuuuuuuuuuuuuuuu对象本身进行处理。这不会以任何方式、形状或形式在实例化时返回
'test'
(尽管考虑到
cl
的示例用法,它似乎解决了OP实际需要的问题).我同意你的看法,它就像一个字符串:d这基本上是相同的答案,但加入了对
\uuuu init\uuuu
不必要的重写。