Austin Joy
Austin Joy

Reputation: 59

Self vs return in Python Classes for Class Attribute

Suppose I have a class attribute in the form of list, and two functions inside that class that append data onto the list for further operations on the list.

Would this be a proper way to write the same:

class Sample:
    def __init__(self):
        self.Mylist = []
        self.customfunc1()
        self.customfunc2()
        self.customfunc3()

    def customfunc1(self):
        somevar = 1
        self.Mylist.append(somevar)
    
    def customfunc2(self):
        somevar = 2
        self.Mylist.append(somevar)

    def customFunc3(self):
        ## Operations on self.Mylist

Or Do I need to return a value after every sub function. I'm new to using 'self' reference so any help appreciated.

Upvotes: 0

Views: 1442

Answers (1)

Ecir Hana
Ecir Hana

Reputation: 11468

It all depends on the intend. When you look, for example, at the standard library (list.append), the convention is that when a method mutates its argument, it does not return anything (i.e. it implicitly returns None). The idea is to make it really obvious that the data was changed.

If, other other hand, the data does not change but you create a new instance, then, well, you don't really have any other option that to return the new instance.

For you example, it is a bit hard to tell as it is a bit artificial but since MyList is an internal implementation detail of the class, I would definitely not return (or the value).

PS: In your example, there are only "instance variables", not "class attribute[s]" - for that the fields would have to be declared one scope above.

Upvotes: 1

Related Questions