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?
I would go for:
This way you are not recomputing the sum each time you call print, its updated when you call the test method.
I am not sure what do you mean by 'and not 11 as I want it'. If you want
Plus(5, 6)
to actually return11
(int
instance), you should makePlus
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.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.
You'd need to define a
__str__
method for yourPlus
class: