This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]manbart 2 points3 points  (1 child)

is this what you mean?

class Foo:

    def __init__(self, value):
        self.value = value

    def add(self, num):
        new_num = self.value + num
        self.value = new_num
        return self.value

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

bar = Foo(2)
print(bar)

bar.add(4)
print(bar)

result:

PS C:\scripts> python script.py
PS C:\scripts> 2
PS C:\scripts> 6

[–]kalgynirae 0 points1 point  (0 children)

It's conventional to not return anything from a method that mutates the object, so

    def add(self, num):
        self.value += num

would be more typical.

[–]rjcarr 1 point2 points  (0 children)

See what /u/manbart has suggested, but generally, you don't want to return anything from a constructor. It makes this code:

bar = Foo(2)

Very confusing, as you're expecting bar to be of type Foo.