0

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.

3
  • It just not related to each other, self is a reference to the class, so if you want that after using your funcs the user will get the modified list you can return it. If not - dont. Most of times when writing set functions usually don't return the modified member Commented Oct 4, 2020 at 9:19
  • @YossiLevi so in the example I showed above , its kinda okay to write it like that? Commented Oct 4, 2020 at 9:24
  • I think that's the way I would do it, when the user is set value to inner member, he usually don't expect to get it back Commented Oct 4, 2020 at 9:30

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes , my bad ,what I meant was mylist is a variable in which data is inserted through the functions below init method and then used in the third subfunction.The way I wrote it, included not returning but using self as it is.Just wanted to know if I dont need the variable instead of just returning could I pass it as I have done above?
"class variable" would mean in your example that the data is global, that's probably not what you wanted. In any case, I would not return anything as it mutates the given instance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.