简体   繁体   English

Python从具有函数的类返回值

[英]Python return value from class with functions

I would like to have a class like this: 我想上这样的课:

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

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

As you can see, I would like to create a class that returns a value on instantiation, but still uses the functions of the class, so like this: 如您所见,我想创建一个在实例化时返回值的类,但仍使用该类的功能,如下所示:

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

If anyone can help me, that would be great! 如果有人可以帮助我,那就太好了!

You want this: 你要这个:

class Test:

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

    def __str__(self):
        return 'test'

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

The method __str__(self) is setting the behavior for the class when used as a string. 当用作字符串时,方法__str__(self)设置类的行为。

I think you're looking for something like this. 我认为您正在寻找类似的东西。

class Test:
    def __init__(self):
        pass

    def __str__(self):
        return 'test'

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

Special Method names could be a good read for you. 特殊方法名称可能是您的理想选择。 https://docs.python.org/3/reference/datamodel.html https://docs.python.org/3/reference/datamodel.html

or maybe this... class TestMe: 也许这是... TestMe类:

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

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

This does not change the MRO or the class type. 这不会更改MRO或类类型。 It still needs some work. 它仍然需要一些工作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM