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
169 views
in Technique[技术] by (71.8m points)

How does Python interpreter look for types?

If I write something like:

>>> a = float()

how does Python interpreter know where to look for type 'float'?

I know that 'float' is a variable defined in Lib/types.py and refers to built-in type types.FloatType. But how does the interpreter build a complete list of all possible types for a script (including user-defined and imported-module-defined)? Which places does it look in? And what do I do to build such a list inside a Python script?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your question seems to be, "How is this a type declaration?" The answer is, it isn't a type declaration. Names in Python have no type associated with them. Names refer to values, and values have a type, determined at runtime.

When Python executes a = float(), it looks up the name float, and finds it in the builtins, it's a function. It calls that function with no arguments. The return value is a float object. The name a is then made to refer to that object. That's all it does. Before it's executed this line of code, Python has no idea what a will become, and it has no idea that floats will be involved.

Python is dynamic, so your line of code could have been in this program:

def float():
    return "I'm not a float!"

a = float()

Now when a = float() is executed, the builtin has nothing to do with it, and there are no floats anywhere, and a refers to a string.

For more on names and values, see Facts and Myths about Python Names and Values.


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

...