Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...