1
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?

1
  • You're not trying to alter the values from a function. You're also printing length, not i.length, which should be causing a NameError since it's undefined at that point. Commented Aug 24, 2020 at 23:37

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

You may also want to note how to call methods as well, since they are doing move(rock.length) instead of rock.move(length)
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.