Reputation: 2224
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?
Upvotes: 3
Views: 4715
Reputation: 1125398
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.
Upvotes: 8