简体   繁体   English

在Python 3.X中具有相同名称的类型和函数?

[英]Types and functions with same name in Python 3.X?

As I understand there are no declaration types in Python. 据我了解,Python中没有声明类型。 When you need an integer or list you would do: 当您需要整数或列表时,您可以执行以下操作:

integer = 5
list_of_integers = [0, 1, 2]

This link to the documentation tells me that int in Python is a built-in function. 指向文档的链接告诉我Python中的int是内置函数。

I'm aware of functions such as str() and int() to convert an integer to string and vice-versa. 我知道诸如str()int()之类的函数可以将整数转换为字符串,反之亦然。

But I have never seen a use of int as a type with dot notation Eg *int.[function_name]* 但是我从未见过将int用作带点符号的类型,例如* int。[function_name] *

How come it can be both a type and a function with the same name? 它怎么可能既是类型又是名称相同的函数? Are there other types such as float , double , and etc. which can be used with dot notation and as well as a function? 是否有其他类型(例如floatdouble等等)可以与点符号以及函数一起使用?

int and str are classes . intstr As with any class in Python, calling it gives you an instance. 与Python中的任何类一样,调用它会为您提供一个实例。 And as with any instance, you certainly can call methods on it. 与任何实例一样,您当然可以在其上调用方法。 int doesn't have that many user-callable methods, but str certainly does: some of the common ones include strip , split , upper , etc. int并没有那么多用户可调用的方法,但str当然可以:一些常见的方法包括stripsplitupper等。

>>> x = str()
>>> x.upper()
''

Edit 编辑

It's still a class. 它仍然是一堂课。 You can do exactly the same with any class, even ones you define yourself: 您可以对任何类进行完全相同的操作,甚至包括您自己定义的类:

>>> class Foo(object):
...   def bar(self):
...     print self.baz
...
>>> f=Foo()
>>> f.baz = 'quux'
>>> f.bar()
quux
>>> Foo.bar(f)
quux

The last operation here is exactly the same idea as calling str.upper(x) 这里的最后一个操作与调用str.upper(x)完全相同。

int and str aren't functions. int和str不是函数。 They are basically data types which in python are actually classes containing different functions of their own. 它们基本上是数据类型,在python中实际上是包含各自不同功能的类。 That's why you can convert an integer to a string using the str(int) method but you can't do the same with int(string) to convert a string to an integer. 这就是为什么您可以使用str(int)方法将整数转换为字符串,但是无法使用int(string)将整数转换为字符串的原因。 And as these are classes one can say that there are different functions (methods) in the class which are in turn use with the dot notation. 由于这些是类,因此可以说该类中有不同的函数(方法),这些函数又与点表示法一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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