Python 3:在__init__内调用类函数 [英] Python 3: Calling a class function inside of __init__

查看:787
本文介绍了Python 3:在__init__内调用类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对python 3有点疑问。

I have a little question about python 3.

我想创建一个类,该类使用该类中的函数。就像:

I want to create a class, which is using a function from within of that class. Just like:

class Plus:
    def __init__(self, x, y):
        self.x = x
        self.y = y

        self.test()

    def test(self):
        return self.x + self.y

现在我正在做类似

a = Plus(5,6)    
print(a)

和python给我

<__main__.Plus object at 0x000000000295F748>

不是我想要的11。我知道我可以得到11 by

and not 11 as I want it. I know that I can get 11 by

a = Plus(5, 6).test()
print(a)

但这不是我想要的。我想在不添加.test()的情况下调用该类并获取结果。

but that's not what I want. I want to call the class and getting the result without adding .test() to it.

您能帮我吗?

推荐答案

您需要定义 __ str __ 方法用于您的 Plus 类:

class Plus:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def test(self):
        return self.x + self.y

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

这篇关于Python 3:在__init__内调用类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆