Python 3: Calling a class function inside of __ini

2019-09-19 11:07发布

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?

4条回答
戒情不戒烟
2楼-- · 2019-09-19 12:01

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楼-- · 2019-09-19 12:06

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楼-- · 2019-09-19 12:08

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.

查看更多
不美不萌又怎样
5楼-- · 2019-09-19 12:13

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())
查看更多
登录 后发表回答