Home > Net >  Python class inheritance dynamic class variable
Python class inheritance dynamic class variable

Time:07-04

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?

CodePudding user response:

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).

  • Related