Python 3: Calling a class function inside of __init__

江枫思渺然 提交于 2019-12-26 03:46:06

问题


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

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.

Can you help me?


回答1:


You'd need to define a __str__ method for your Plus class:

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



回答2:


I would go for:

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

This way you are not recomputing the sum each time you call print, its updated when you call the test method.




回答3:


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.

I am not sure what do you mean by 'and not 11 as I want it'. If you want Plus(5, 6) to actually return 11 (int instance), you should make Plus a function that returns the sum. Alternatively you can override __new__ method and hook upon object creation -- but this is a bad idea.

What are you trying to achieve?

I doubt, that by 'and not 11 as I want it' you want something special to be printed (formatted, represented). If so, override __str__ or __unicode__ or __repr__ method.




回答4:


Edit: ignore this answer, it is a comment on a misinterpretation of the question

This is just wrong. when you instantiate an object, you'd expect to get a reference to that object.

if you just want a global function returning a number, why even bother to make a class with an init?

in python you shouldn't want static class's like in C# for encapsulation. instead name the module something, and use that for encapsulation.



来源:https://stackoverflow.com/questions/33802346/python-3-calling-a-class-function-inside-of-init

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!