Eliav Louski
Eliav Louski

Reputation: 5264

python class not recognize class declared inside of her

this question must be a stupid one but important one and couldn't find any discussion about this in stackoverflow.

I'm trying to declare a class (lets say class 'B') inside another class (lets say 'A'), and use that class('B') in a method of class 'A', but for some reason in python you cannot declare an object member of class type that is declared in the same class.

why is that the case? in C you can access to the inner class from a method of the outside class without any problem... (my intention that is only class A will ever need a member of type class B and i want only A to be able to find out that such a class like B...)

what is the proper way to do so in python?

class A:
    def __init__(self):
        self.B_object = B()    # error 'unresolved refernace B'

    class B:
        def __init(self):
            pass

Upvotes: 0

Views: 158

Answers (1)

Vashdev Heerani
Vashdev Heerani

Reputation: 679

class A:
    def __init__(self):
        self.B_object = A.B()

    class B:
        def __init(self):
            pass

Try this if you want to make B class private you can try this

class A:
    def __init__(self):
        self.__B_object = A.__B()

    class __B:
        def __init__(self):
            pass

Upvotes: 1

Related Questions