0

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?

4
  • I don't understand why you're saying _type is a str in the first place if you want it to be something that has a name attribute... Commented Jul 3, 2022 at 22:23
  • Just fixed the typing error. @Samwise. _type is a class. Commented Jul 3, 2022 at 22:24
  • You could define __init__() and put the name on the instance when the instance is initialized? Although it's not clear what should happen when someone creates Base(). Commented Jul 3, 2022 at 22:28
  • As long as you don't need a._type.name to work ,only a_instance._type.name, initialize the attributes in a's __init__ method. If you need it to work on a itself, put it in the metaclass. Commented Jul 3, 2022 at 22:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. You didn't have all the information to give me a specific answer, but you helped me a lot and I solved the problem with your help. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.