I have recently tried to get into OOP to take a step into more advanced python. I wanted to do a list of functions in a class. I started by not using self.functionName = functionName, this led to an error where the functions could not be identified in the list. So I assumed that what you write in the __init__ function works as global function in the class, so I added self to the first two functions so that they could be used in the other function, and it worked fine. However when I added self to the last functions I did not get the same answer, why is that?
This is the code that I wrote:
>>> class number: #works fine, no self.ans
def __init__(self):
self.numOne = numOne
self.numTwo = numTwo
def numOne(self):
print("one")
def numTwo(self):
print("two")
def ans(self):
bruh = [numOne, numTwo]
for i in bruh:
i()
>>> a = number()
>>> a.ans()
one
two
>>> class number: #now when I write self.ans
def __init__(self):
self.numOne = numOne
self.numTwo = numTwo
self.ans = ans
def numOne(self):
print("one")
def numTwo(self):
print("two")
def ans(self):
bruh = [numOne, numTwo]
for i in bruh:
i()
>>> a = number()
>>> a.ans()
<generator object ans.<locals>.<genexpr> at 0x0000021476FDBF90> #this is the result
>>>
>Solution :
You don’t need to assign the methods to the instance in the constructor. That’s part of how classes work already.
This works correctly:
class Number:
def num_one(self):
print("one")
def num_two(self):
print("two")
def ans(self):
bruh = [self.num_one, self.num_two]
for i in bruh:
i()
n = Number()
n.ans()
Result:
one
two
Of course, you can still have an __init__ if you need to set some initial values, but a class doesn’t require a custom constructor. Just by declaring it as a class, it will have a constructor that you can override as needed.
By the way, you would do well to name your classes with names starting with a capital letter. Naming the methods with camel-case is more of a taste-thing, but I feel the underscore is more pythonic – the capital is definitely something to use however, to avoid people confusing objects and classes.