0

I need class with possibility of create other class instances and self instances in class method scope. I have following code:

class A:
    #somme stuff

class B:
    allowed_children_types = [ #no reason to make self.allowed_children_types
        A,
        C #first problem, no C know
    ]

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects


class C:
    allowed_children_types = [  # no reason to make self.allowed_children_types
        A,
        B
        C  # second problem, no C know because type object is not yet created
    ]

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects

I will not create independent factory because it will complicated very simple application logic. I feel that create custom metaclass is usually bad designe.

What should I do to jump over this issue?

2
  • You can only refer to a name if it has been defined. After you class definitions, assign the class variables Commented Dec 22, 2020 at 13:48
  • Sounds like an XY problem. Please provide information about what you actually want to do. Why can't you use a classmethod? Commented Dec 22, 2020 at 14:07

1 Answer 1

1

You have to have all those names defined before you use them. Something like:

class A:
    #somme stuff

class B:

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects


class C:

    @staticmethod
    def foo(self):
        #use allowed_children_types to create children objects

B.allowed_children_types = [A, C]
C.allowed_children_types = [A, B, C]
Sign up to request clarification or add additional context in comments.

1 Comment

Dirty solution (i want a bit more clean solution) but enough for me.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.