3
class first(object):
    def __init__(self, room, speed):
        self.position = room
        self.speed = 20
        direction = random.randint(0,359)
class second(first):
    def __init__(self)
        self.way = first.direction
        self.now = first.self.position

I am getting an error, how to get variable from __init__ of another class?

1 Answer 1

8

You cannot. direction is a local variable of the __init__ function, and an such not available outside of that function.

The variable is not used at all even; it could be removed from the function and nothing would change.

The __init__ method is intended to set attributes on the newly created instance, but your second class seems to want to find the attributes on the first class instead. You cannot do that either, as those attributes you want to access are only set in __init__. You can only find position on instances of first, not on the first class itself.

Perhaps you wanted to initialize the parent class first, and actually store position on self:

class first(object):
    def __init__(self, room, speed):
        self.position = room
        self.speed = 20
        self.direction = random.randint(0,359)

class second(first):
    def __init__(self, room, speed)
        super(second, self).__init__(room, speed)
        self.way = self.direction
        self.now = self.position

Now self has the direction and position attributes defined and your second.__init__ function can access those there.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for the edit guessing what the OP really wants. I was putting together the same code but you beat me :)

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.