Search code examples
pythonclassinitself

python class self and __init__


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.


Solution

  • 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).