简体   繁体   中英

Python string to float conversion

Can someone explain why the x below can act as a function float()? Basically I dont understand what means? is this a internal function or implicit object ?

>>> x=type(0.0)
>>> x
<type 'float'>
>>> x('9.823')
9.823

It's exactly the same as writing float('9.823') . In fact, you can easily see that as follows:

>>> type(0.0) is float
True
>>> 

And you can use them in exactly the same way:

>>> float('9.823')
9.823
>>> type(0.0)('9.823')
9.823
>>> 

It's just invokes the constructor for the float type.

You're setting the variable x to the type float . The command type() returns the type of whatever is inside the brackets. In your case, you provided the type command with a float and setting that return of float to your variable x .

It can act as the function float because you are effectively making x = float .

As an example, you could also, for instance do this:

x = type(1) #int
print x(1.1111) # will print 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM