简体   繁体   中英

Global variable through classes?

I'm trying to call a method of a class using a global variable, but there seems to be something wrong with my logic.

In the code below, A calls B which calls C which calls a method of B .

x = None

class A():

    def __init__(self):

        global x
        x = B()

class B():

    def __init__(self):

        C()

    def bla(self):

        print('bla')

class C():

    def __init__(self):

        global x
        x.bla()

A()

The error I'm getting:

AttributeError: 'NoneType' object has no attribute 'bla'

What am I missing?

When you do x = B() , the result of calling B() cannot be assigned to x until after B is finished initialized. But B.__init__() is called when you create the B instance, and it immediately calls C() . In other words, when you do x = B() , things happen in this order:

  1. call B.__init__()
  2. call C.__init__() (because of C() call in B.__init__() )
  3. assign result of B() to x .

But step 3 never happens, because C.__init__() raises an error, because step 3 hasn't happened yet so the object hasn't been assigned to x yet.

It's not clear what you're trying to accomplish here, so it's hard to say how best to change your code. There is no way for C.__init__ to make use of a variable that will not be defined until after C.__init__ finishes running.

Here is your problem

you say x = b() well, x is None until b finishes initializing... which also means until c finishes initializing, which would cause a problem in class C when you do

x.bla()

This is because x is not completely initialized until it finishes calling the init function for each class. Here you tried to access global x, before completing its initialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM