Python 是强类型的吗? [英] Is Python strongly typed?

查看:70
本文介绍了Python 是强类型的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现一些链接说 Python 是一种强类型语言.

I've come across links that say Python is a strongly typed language.

然而,我认为在强类型语言中你不能这样做:

However, I thought in strongly typed languages you couldn't do this:

bob = 1
bob = "bob"

我认为强类型语言在运行时不接受类型更改.也许我对强/弱类型的定义有误(或过于简单化).

I thought a strongly typed language didn't accept type-changing at run-time. Maybe I've got a wrong (or too simplistic) definition of strong/weak types.

那么,Python 是强类型语言还是弱类型语言?

So, is Python a strongly or weakly typed language?

推荐答案

Python 是强动态类型的.

Python is strongly, dynamically typed.

  • 类型意味着值的类型不会以意想不到的方式改变.只包含数字的字符串不会像在 Perl 中那样神奇地变成数字.每次类型更改都需要显式转换.
  • 动态类型意味着运行时对象(值)有一个类型,而不是静态类型,其中变量有一个类型.
  • Strong typing means that the type of a value doesn't change in unexpected ways. A string containing only digits doesn't magically become a number, as may happen in Perl. Every change of type requires an explicit conversion.
  • Dynamic typing means that runtime objects (values) have a type, as opposed to static typing where variables have a type.

至于你的例子

bob = 1
bob = "bob"

这是可行的,因为变量没有类型;它可以命名任何对象.在bob=1之后,你会发现type(bob)返回的是int,但是在bob="bob",它返回str.(请注意,type 是一个常规函数,因此它会评估其参数,然后返回值的类型.)

This works because the variable does not have a type; it can name any object. After bob=1, you'll find that type(bob) returns int, but after bob="bob", it returns str. (Note that type is a regular function, so it evaluates its argument, then returns the type of the value.)

将此与较旧的 C 方言进行对比,后者是弱静态类型的,因此指针和整数几乎可以互换.(现代 ISO C 在很多情况下都需要转换,但我的编译器在默认情况下对此仍然很宽容.)

Contrast this with older dialects of C, which were weakly, statically typed, so that pointers and integers were pretty much interchangeable. (Modern ISO C requires conversions in many cases, but my compiler is still lenient about this by default.)

我必须补充一点,强类型与弱类型更像是一个连续体,而不是布尔选择.C++ 比 C 具有更强的类型化(需要更多的转换),但可以通过使用指针强制转换来颠覆类型系统.

I must add that the strong vs. weak typing is more of a continuum than a boolean choice. C++ has stronger typing than C (more conversions required), but the type system can be subverted by using pointer casts.

Python 等动态语言中类型系统的强度实际上取决于其原语和库函数对不同类型的响应方式.例如,+ 被重载,因此它可以处理两个数字 两个字符串,而不是一个字符串和一个数字.这是在实现 + 时做出的设计选择,但并不是遵循语言语义的必要条件.事实上,当你在自定义类型上重载 + 时,你可以让它隐式地将任何东西转换为数字:

The strength of the type system in a dynamic language such as Python is really determined by how its primitives and library functions respond to different types. E.g., + is overloaded so that it works on two numbers or two strings, but not a string and an number. This is a design choice made when + was implemented, but not really a necessity following from the language's semantics. In fact, when you overload + on a custom type, you can make it implicitly convert anything to a number:

def to_number(x):
    """Try to convert function argument to float-type object."""
    try: 
        return float(x) 
    except (TypeError, ValueError): 
        return 0 

class Foo:
    def __init__(self, number): 
        self.number = number

    def __add__(self, other):
        return self.number + to_number(other)

Foo 类的实例可以添加到其他对象中:

Instance of class Foo can be added to other objects:

>>> a = Foo(42)
>>> a + "1"
43.0
>>> a + Foo
42
>>> a + 1
43.0
>>> a + None
42

请注意,尽管强类型 Python 完全可以添加 intfloat 类型的对象并返回 float 类型的对象(例如,int(42) + float(1) 返回 43.0).另一方面,由于类型之间的不匹配,如果尝试以下 (42 :: Integer) + (1 :: Float),Haskell 会抱怨.这使得 Haskell 成为一种严格类型化的语言,其中的类型是完全不相交的,并且只能通过类型类实现受控的重载形式.

Observe that even though strongly typed Python is completely fine with adding objects of type int and float and returns an object of type float (e.g., int(42) + float(1) returns 43.0). On the other hand, due to the mismatch between types Haskell would complain if one tries the following (42 :: Integer) + (1 :: Float). This makes Haskell a strictly typed language, where types are entirely disjoint and only a controlled form of overloading is possible via type classes.

这篇关于Python 是强类型的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆