Python 3: 在 __init__ 中调用一个 class 函数

Python 3: Calling a class function inside of __init__

我有一个关于python3的小问题。

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

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
a = Plus(5, 6).test()
print(a)

但这不是我想要的。我想调用 class 并在不向其添加 .test() 的情况下获得结果。

你能帮帮我吗?

您需要为 Plus class 定义 __str__ method:

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

我会选择:

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

        self.test()

    def test(self):
        res = self.x + self.y
        self.__repr__ = lambda:str(res)
        return res

>>> Plus(5,5)
10
>>> a = Plus(5,5)
>>> a
10
>>> a.test()
10

这样你就不会在每次调用 print 时重新计算总和,它会在你调用测试方法时更新。

编辑: 忽略这个答案,这是对错误解释问题的评论

这是完全错误的。 当您实例化一个对象时,您会期望获得对该对象的引用。

如果你只是想要一个返回数字的全局函数,为什么还要用 init 创建一个 class?

in python 你不应该像 C# 中那样使用 static class 进行封装。取而代之的是给模块命名,并将其用于封装。

now I am doing something like

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

and python is giving me

<__main__.Plus object at 0x000000000295F748>

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

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

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

我不确定 'and not 11 as I want it' 是什么意思。如果你想让 Plus(5, 6) 实际上 return 11int 实例),你应该使 Plus 成为 return 求和的函数。或者,您可以覆盖 __new__ 方法并挂钩对象创建——但这是个坏主意。

你想达到什么目的?

我怀疑 'and not 11 as I want it' 你想要一些特别的东西被 印刷 (格式化,表示)。如果是这样,请覆盖 __str____unicode____repr__ 方法。