Bolaji Bolaji - 1 year ago 59
Python Question

Function cannot be called in another function with both fucntions in the same class

Im learning about OOP in Python and I wrote this code,I tried executing a function in another,both of which belongs to the same class but it gave an error message.The code is

class dumb(object):
def __init__(money,price):
global kudi
kudi = 28

def dear(money):
print 'kudi is=%s'%kudi
if int(kudi) == 28:
s = 'champagne'
print "Kudi != 28"

def faithful(money):
print 'kudi is:%s'%(kudi*3)

something = dumb(int(raw_input('>')))

Gave an error message of
NameError: global name 'faithful' is not defined
.I tried it for an external function outside the class and it worked well.How can I make this work?

Answer Source

There are some mistakes in your code.

From there on, I will assume that you wanted to make dear and faithful member functions, that is functions applicable for the dumb class because you tried to call something.dumb()

  • Member functions have a reference to self as their first arguments. dear(money) should be dear(self, money) and faithful(money) should be faithful(self, money)
  • When calling faithful(s), you are trying to call a global function (defined outside the class) with s as argument. To call the faithful function of the dumb class, the syntax is self.faithful(s)
  • At the end of the file, you are trying to call something.dear() which doesn't work because dear takes an argument
  • Do not use global variables in OOP. Make kudi an attribute of dumb or whatever, but not a global variable.