![]() |
can Inner Class reference the Outer Class's static variable? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: can Inner Class reference the Outer Class's static variable? (/thread-36701.html) |
can Inner Class reference the Outer Class's static variable? - raykuan - Mar-20-2022 In the nested class, can Inner Class reference the Outer Class's static variable? class Outer(object): a = 111 class Inner(object): b = Outer.a. # NameError: name 'Outer' is not defined @staticmethod def get_a(cls): return Outer.a # OK RE: can Inner Class reference the Outer Class's static variable? - Larz60+ - Mar-20-2022 why make your code complicated? why not: class Outer(object): def __init__(self): self.a = 111 print(f"Outer.a = {Outer().a}")
RE: can Inner Class reference the Outer Class's static variable? - Gribouillis - Mar-20-2022 You can do this class Outer(object): a = 111 class Inner(object): @staticmethod def get_a(cls): return Outer.a # OK Inner.b = a RE: can Inner Class reference the Outer Class's static variable? - deanhystad - Mar-21-2022 Class variable, not static variable. This is Python, not C++. The answer to your question is yes and no. You cannot use class variables in Outer when assigning class variables in Inner because class Outer does not exist yet when you create class variables for Inner. However, methods in Inner can see Outer just fine. class Outer(object): a = 1 class Inner(object): a = 2 @classmethod def aay(cls): return cls.a, Outer.a print(Outer.Inner.aay()) This also works for instance methods of Inner.
RE: can Inner Class reference the Outer Class's static variable? - raykuan - Mar-22-2022 Find a way to handle it now, using inheritance class _(object): a = 100 class Outer(_): class Inner(object): b = _.a # OK @staticmethod def get_a(cls): return Outer.a # OK RE: can Inner Class reference the Outer Class's static variable? - deanhystad - Mar-22-2022 What are you trying to achieve? I was confused by your original post and more confused now. Why do you want a class variable in Inner that is initialized to the value of a class variable in Outer? I don't see how this makes any sense. Could you please describe the purpose for this? RE: can Inner Class reference the Outer Class's static variable? - SharonDutton - Jul-01-2022 Unlike inner class, a static nested class cannot access the member variables of the outer class. It is because the static nested class doesn't require you to create an instance of the outer class. OuterClass. NestedClass obj new OuterClass.We can not have a « url snipped » static method in a nested inner class because an inner class is implicitly associated with an object of its outer class so it cannot define any static method for itself. For example, the following program doesn't compile. |