i have the following code and any trying to make a class that generates two random numbers in a list and returns them
import random
class add :
def __init__(self):
self.data = []
def GenerateLocation(self):
random1 = 10
random2 = 20
self.data.append(random.uniform(-random1 , random1))
self.data.append(random.uniform(-random2 , random2))
print(self.data)
self.data.GenerateLocation(self)
I get the error self is not defined in line 15
the self.data.GenerateLocation(self).
Can anyone explain this, I've look at the other questions on self and init but its over my head.
2 Answers 2
I think you try to do this:
import random
class Add:
def __init__(self):
self.data = []
def generate_location(self):
random1 = 10
random2 = 20
self.data.append(random.uniform(-random1 , random1))
self.data.append(random.uniform(-random2 , random2))
print(self.data)
my_object = Add()
my_object.generate_location()
To use class you have to create object/instance. Creating instance python calls Add.__init__ and reserves place in memory for self.data. Then you can call its method my_object.generate_location() and it can use self.data.
self is use only inside class - it is like words me, my (my.data).
1 Comment
The line self.data.GenerateLocation(self) is really strange and it is not clear what are you trying to do here. If you are creating the class, it seems that you want to instantinate it, i.e. create object of that class. To do so, you have to invoke constructor. In your case it will be like (copying from @furas's answer)
my_object = Add()
This creates object my_object which is instance of class Add. Then you can call method generate_location of your object. To do so, you have to prepend generate_location() with the name of your object.
my_object.generate_location()
Note that despite the fact that generate_location has argument self, it is not given explicitly in this call. This is because Python will pass (a reference to) the object my_object to the method generate_location as a first argument automatically just because it is method of this object. (Methods are functions that are associated with objects, like .append() for lists.)
See the official tutorial for more details: python 2, python 3.
GenerateLocation()method onself.data, which is a list object.selfto be, and why?selfis an argument to a method. The main program is not a method, so there is noselfthere. Did you mean to create an instance of the class and call the method on that? If so, you'll need to do that:instance = add(),add.GenerateLocation(). Theselfargument is going to be taken care of for you in that case.