r366y
r366y

Reputation: 381

How assign to a class attribute an instance from another class residing on the same module

I cannot figure out to solve this problem:

class Clazz:
    EMPTY=Clazz1(None,None)

    def __init__(self):
        self.item=Clazz1("a","b")

class Clazz1:
    def __init__(self,key,value):
        self.key=key
        self.value=value

if __name__=='__main__':
   h=Clazz()

When I try to run it returns :

Traceback (most recent call last):
  File "C:\Users\Desktop\test.py", line 1, in <module>
   class Clazz:
  File "C:\Users\Desktop\test.py", line 2, in Clazz
    EMPTY=Clazz1(None,None)
NameError: name 'Clazz1' is not defined

Any idea? Thanks in advance

Upvotes: 1

Views: 83

Answers (4)

pmav99
pmav99

Reputation: 2057

Just change the order of the classes (and read about the order of execution in python). You may find this helpful http://pythontutor.com/visualize.html

class Clazz1:
    def __init__(self,key,value):
        self.key=key
        self.value=value


class Clazz:
    EMPTY=Clazz1(None,None)

    def __init__(self):
        self.item=Clazz1("a","b")


if __name__=='__main__':
    h=Clazz()

Upvotes: 2

glglgl
glglgl

Reputation: 91059

At the time where it is needed, Clazz1 does not exist yet.

Class definitions are executed immediately, so Clazz1 must be defined before Clazz.

Note the difference to a fuinction definition, where the referred names must exist at run time:

def func():
    test = func1()

def func1():
    pass

if __name__=='__main__':
   func()

When func() is finally called at the end, func1() exists so that it can perfectly be called.

Upvotes: 1

Grzegorz Piwowarek
Grzegorz Piwowarek

Reputation: 13803

You should put the Clazz1 definition before the Clazz. If You don't do this Clazz can't see the Clazz1

Upvotes: 2

Pavel Anossov
Pavel Anossov

Reputation: 62928

Clazz1 has to be defined before Clazz:

class Clazz1:
    def __init__(self, key, value):
        self.key = key
        self.value = value


class Clazz:
    EMPTY = Clazz1(None, None)

    def __init__(self):
        self.item = Clazz1("a", "b")


if __name__ == '__main__':
   h = Clazz()

Upvotes: 3

Related Questions