I'm trying to run this code but I'm getting an error msg ---> "NameError: name 'generateRandom' is not defined"
Can anyone help me please?
`import numpy as np
class Mul:
def __init__ (self,ra_result=None,rb_result=None):
self.ra_result = ra_result
self.rb_result = rb_result
def generateRandom():
return np.random.randint(0,2**32), np.random.randint(0,2**32)
def Multi_test(self):
self.ra_result,self.rb_result= generateRandom()
print("expected_output (python) = ")
print("ra=",self.ra_result,"rb=",self.rb_result," (ra*rb)=")
return self.ra_result*self.rb_result
object = Mul()
object.Multi_test()`
CodePudding user response:
You have to use keyword self
to let your class know you are using a method of itself.
You have to specify the self
when calling the function self.generateRandom()
and also you need to either specify when creating the function that it takes self as an argument, but since you have a static method, you can wrap it in @staticmethod
This is a working versio of your class Mul
class Mul:
def __init__ (self,ra_result=None,rb_result=None):
self.ra_result = ra_result
self.rb_result = rb_result
@staticmethod
def generateRandom():
return np.random.randint(0,2**32), np.random.randint(0,2**32)
def Multi_test(self):
self.ra_result,self.rb_result = self.generateRandom()
print("expected_output (python) = ")
print("ra=",self.ra_result,"rb=",self.rb_result," (ra*rb)=")
return self.ra_result*self.rb_result
CodePudding user response:
I am not going to discuss why you have written your code in this way and directly talk about your error. You are getting this error because generateRandom is a method within Mul class. To refer to the other methods of the same class within a method, you should use 'self'. Additionally add static method since generateRandom doesn't use self. It would also be good if you could improve how you name variables, methods etc. The code will look like below \
import numpy as np
class Mul:
def __init__ (self,ra_result=None,rb_result=None):
self.ra_result = ra_result
self.rb_result = rb_result
@staticmethod
def generateRandom():
return np.random.randint(0,2**32), np.random.randint(0,2**32)
def Multi_test(self):
self.ra_result,self.rb_result= self.generateRandom()
print("expected_output (python) = ")
print("ra=",self.ra_result,"rb=",self.rb_result," (ra*rb)=")
return self.ra_result*self.rb_result
my_object = Mul()
my_object.Multi_test()
CodePudding user response:
The function you're trying to call, is itself a class function, I.E. it needs to be called like this:
self.generateRandom()
Edit: You could make the generateRandom() an internal private function, by changing it to
def __generateRandom(self):
...
rng = self.__generateRandom()
In this case you can easily access it and it's still out of reach