Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python class inheritance dynamic class variable

This is what I want to do:

class Base:
    _type = None
    name: str = _type.name

class a(Base):
    _type = UnityType

a_instance = a()
a_instance.name  # Expecting UnityType.name to be some string.

While trying this, I get 'NoneType' object has no attribute 'name'. The reason is clear and understandable. But how can I pass the responsibility of implementing a variable class to a subclass?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I think you need Base.name to be a property, so that it’s evaluated when it’s accessed rather than when Base is defined:

from typing import Optional, Protocol, Type

class Named(Protocol):
    name: str

class Base:
    _type: Optional[Type[Named]] = None

    @classmethod
    @property
    def name(cls) -> str:
        assert cls._type is not None
        return cls._type.name

class UnityType:
    name = "Unity"

class a(Base):
    _type = UnityType

a_instance = a()
print(a_instance.name)  # prints "Unity"

I’m assuming from your example that UnityType is a type, not an instance, and that you want Base to work with either that type or other types with a name class attribute, so I defined a Protocol that requires that and used that for the type annotation of Base (the above passes mypy without complaint).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading