Python, OOP | Sololearn: Learn to code for FREE!


Python, OOP

class Pocket: def myMoney(self): return '$100' a=Pocket() print(a.myMoney()) #What I want to ask here is that can we assume these functions here as variable? Can we reassign them? a.myMoney()='00' #or: a.myMoney='00'

9/2/2019 5:36:10 AM

Harshit Garg

1 Answer

New Answer


In Python, all is object, so function can be transformed into other data types (int, list, other functions). I think that you want to change the return value of myMoney, isn't it? First, a.myMoney() = '00' can't work. It is like if you do 2 = 3, it has no sense. Second, a.myMoney = '00' works BUT myMoney is not a function anymore. After that a.myMoney() is not valid, because a.myMoney is now a string. The best thing is to create an attribute called amount. class Pocket: def __init__(self) : self.amount = '100' def myMoney(self) : return self.amount def setMoney(self, q) : self.amount = q Explanations: __inti__ is the constructor of class Money. It is called when creating a new object. Here, you declare a new class attribute called 'amount' that will store the current money. When you call myMoney, you return the current money. When you want to change the amount of money, you call method setMoney.