germanpogostick
germanpogostick

Reputation: 11

How to alter values in a class from within a function?

class Rock:
    def __init__(self, length, width):
        self.length = length
        self.width = width
    def move(length):
        length = length + 1


rock1 = Rock(100,300)
rock2 = Rock(300,500)
rocklist = [rock1,rock2]
gameover = 1
counter = 0
while gameover == 1:
    for i in rocklist:
        move(i.length)
        print(length)

When running this, length remains the same, as demonstrated by the print. How can I change the values using a function?

Upvotes: 1

Views: 47

Answers (2)

itismoej
itismoej

Reputation: 1847

There is an object self for all object methods that references to object itself:

def move(self, movement_amount):
    self.length += movement_amount

You can call object methods from the object itself:

rock1 = Rock(100,300)
rock1.move(1)  # Increase the length of this object by 1

In your case:

while gameover == 1:
    for rock in rocklist:
        rock.move(1)
        print(rock.length)

Upvotes: 3

xszym
xszym

Reputation: 938

You can create move function as a class function and then use it on the each rock object. This is how code structure will look like:

class Rock:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def move(self):
        self.length = self.length + 1

rock1 = Rock(100,300)
rock2 = Rock(300,500)
rocklist = [rock1,rock2]
gameover = 1
counter = 0
while gameover == 1:
    for rock in rocklist:
        rock.move()
        print(rock.length)

Upvotes: 1

Related Questions