Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Abstract class attribute in Python? [duplicate]

I have a class like this

from abc import ABC

class AbstractFoo(ABC):
  # Subclasses are expected to specify this
  # Yes, this is a class attribute, not an instance attribute
  bar: list[str] = NotImplemented  

# for example
class SpecialFoo(AbstractFoo):
  bar = ["a", "b"]

But this does not feel particularly clean and perhaps a little confusing. Importantly, the bar attribute is nowhere marked as abstract, so it could be still possible to instantiate it without being specified. Is there a better way to achieve a similar behavior?

like image 864
user344577 Avatar asked May 21 '26 07:05

user344577


1 Answers

Just don't specify a value, to keep it as an annotation?

from abc import ABC

class AbstractFoo(ABC):
  bar: list[str] 


class SpecialFoo(AbstractFoo):
  bar = ["a", "b"]
like image 110
AKX Avatar answered May 23 '26 20:05

AKX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!