Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting __init__ variable

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?

like image 229
Ivan Vulović Avatar asked Apr 12 '26 00:04

Ivan Vulović


1 Answers

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.

like image 167
Martijn Pieters Avatar answered Apr 13 '26 14:04

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!