Search code examples
pythonpython-3.xsubclassingprivate-members

Which is the correct way of using a class method into its subclass that maybe won't be instantiated?


Given the parent class:

class Parent():
   _private_attr: Int = None

   @classmethod
   def set_private_attr(cls, value):
      if not type(value) is int:
         raise ValueError()
      cls._private_attr = value

How do I use set_private_attr into a subclass, given that maybe it will not be instantiated and therefore I can't use super() in __init__?

E.g.:

def SubClass(Parent):
   Parent.set_private_attr(a_value)

Is that right? There's is a better way of doing this?


Solution

  • You need to inherit from Parent, then the derived class can use the set_private_attr() class method.

    Here's an example.

    class Parent():
       _private_attr = None
    
       @classmethod
       def set_private_attr(cls, value):
          cls._private_attr = value
    
    class Foo(Parent):
        pass
    
    foo = Foo()
    foo.set_private_attr("bar")
    

    If you want to set this before constructing the derived class:

    Foo.set_private_attr("bar")
    foo = Foo()
    print(foo._private_attr)