Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

python - Get annotated instance variables

PEP 526 introduced syntax for variable annotations, that can be added on an instance variable even when the value is not defined.

class BasicStarship:
    captain: str = 'Picard'               # instance variable with default
    damage: int                           # instance variable without default

But when I list the instance variables, the one without value is not listed:

starship = BasicStarship()
dir(starship) #doesn't return 'damage' field

How can I get all instance variable, including the ones without value?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

__annotations__ shows it:

>>> starship.__annotations__
{'captain': <class 'str'>, 'damage': <class 'int'>}

A dict containing annotations of parameters. The keys of the dict are the parameter names, and 'return' for the return annotation, if provided.

Although, note, from your link:

[T]he value-less notation a: int allows one to annotate instance variables that should be initialized in __init__ or __new__.

So, you should be setting it anyway if you're going to do that, in which case it will show up in dir.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...