强类型、弱类型与动态类型

原创 2003年07月16日 13:58:00
与一些传言不同,Python是一种强类型的语言,但它又是动态类型的。强类型、动态类型、弱类型,这是几个不同(而又经常混淆)的概念。
 
————————————————

Typing: Strong vs. Weak, Static vs. Dynamic


by Aahz
July 15, 2003
Summary
With the advent of languages such as Python, the debate over typing has heated up again. Contrary to some claims (notably from Bruce Eckel), I believe Python has strong typing, and this article explains why.

What is a "type", anyway?

Before talking about what kind of type system a language supports, we should establish agreement about what a type is in the first place. My definition is that a type is metadata about a chunk of memory that classifies the kind of data stored there. This classification usually implicitly specifies what kinds of operations may be performed on the data.

Common types include primitive types (strings and numbers), container types (lists/arrays and dictionaries/hashes), and user-defined types (classes). In Python, everything is an object, and every object has a type. In other words, functions, modules, and stack frames are also types.

So what's "strong typing", then?

From my POV, strong typing prevents mixing operations between mismatched types. In order to mix types, you must use an explicit conversion. Here's a simple Python example:

>>> 1 + "1"
Traceback (most recent call last):
  File "", line 1, in ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> 1 + 1
2
>>> "1" + "1"
'11'
>>> 1 + int("1")
2
>>> "1" + str(1)
'11'

Conversely, weak typing means that you can mix types without an explicit conversion. Consider this example from Perl:

  DB<1> print "1"+1
2
  DB<2> print "1".1
11

Note that conversion is not the same thing as coercion, IMO. Coercion occurs when you have a statically-typed language and you use the syntactic features of the language to force the usage of one type as if it were a different type (consider the common use of void* in C). Coercion is usually a symptom of weak typing. Conversion, OTOH, creates a brand-new object of the appropriate type.

Why do some people think Python has weak typing?

Historically, "strong typing" has been associated with static typing. Languages noted for strong typing include Pascal and Ada; languages noted for weak typing (most notoriously BASIC) had primarily dynamic typing. But the language that ought to be most notorious for weak typing has static typing: C/C++ (yes, I'm lumping them together)

It's very clear that Python has only dynamic typing; any target may hold a binding to any kind of object. More than that, Pythonic programming style is to use inheritance primarily for implementation; Python's name-based polymorphism means that you rarely need to inherit for interface. In fact, the primary exception to inheriting for implementation is Python exceptions, which uses issubclass() for the purpose of determining which exceptions get caught by an except clause.

I might even go so far as to say that Python's name-based polymorphism is hyperpolymorphic. And therein lies the tiny kernel of truth about Python's weak typing. People who have gotten used to Java and C++ requiring syntactic support to declare typing often feel uncomfortable with the Pythonic style of relying on run-time exceptions to get thrown when an inappropriate object is passed around:

class Silly:
    def __init__(self, data):
        self.data = data
    def __add__(self, other):
        return str(self.data) + str(other.data)

def double(a):
    return a + a

print double(1)
print double('x')
print double([1])
print double(Silly({'a':1}))
print double({'a':1})
produces
2
xx
[1, 1]
{'a': 1}{'a': 1}
Traceback (most recent call last):
  File "test.py", line 14, in ?
    print double({'a':1})
  File "test.py", line 8, in double
    return a + a
TypeError: unsupported operand types for +: 'dict' and 'dict'

Bruce Eckel equates "weak typing" with "latent typing", but that's at odds with historical usage, not to mention that it confuses the two axes of strong/weak and static/dynamic.

CSDN_Dev_Image_2003-7-161315281.gif

Sidebar: Name-based polymorphism

For those of you unfamiliar with Python, here's a quick intro to name-based polymorphism. Python objects have an internal dictionary that contains a string for every attribute and method. When you access an attribute or method in Python code, Python simply looks up the string in the dict. Therefore, if what you want is a class that works like a file, you don't need to inherit from file, you just create a class that has the file methods that are needed.

Python also defines a bunch of special methods that get called by the appropriate syntax. For example, a+b is equivalent to a.__add__(b). There are a few places in Python's internals where it directly manipulates built-in objects, but name-based polymorphism works as you expect about 98% of the time.

Resources

Discussions of types

TUNES : Type System
http://cliki.tunes.org/Type%20System

type from FOLDOC
http://wombat.doc.ic.ac.uk/foldoc/foldoc.cgi?type

Python & Java: Side by Side Comparison
http://www.ferg.org/projects/python_java_side-by-side.html

Bruce Eckel and Python's weak typing

Artima Interview: Type Checking and Techie Control
http://www.artima.com/intv/typing.html

Strong Typing vs. Strong Testing
http://mindview.net/WebLog/log-0025

Talk Back!

Have an opinion? Be the first to post a comment about this weblog entry.

RSS Feed

If you'd like to be notified whenever Aahz adds a new entry to his weblog, subscribe to his RSS feed.

About the Blogger

Aahz has been using Python since 1999. He helps people on comp.lang.python, and is one of the webmasters for www.python.org. Aahz focuses on the Python object model and Python threads. Aahz is currently working on "Effective Python" for Addison Wesley.

This weblog entry is Copyright © 2003 Aahz. All rights reserved.

弱类型、强类型、动态类型、静态类型语言的区别是什么?

类型系统的一些概念,众说纷纭,使用上也比较乱。有些东西,甚至不好严格定义。以下算学术界的一种相对“严格”的说法。 1. 先定义一些基础概念 Program Errors trapped errors...
  • sisyphus_z
  • sisyphus_z
  • 2016年07月18日 15:25
  • 1734

强类型语言和弱类型语言

编译型和解释型   我们先看看编译型,其实它和汇编语言是一样的:也是有一个负责翻译的程序来对我们的源代码进行转换,生成相对应的可执行代码。这个过程说得专业一点,就称为编译(Compile),而负责编...
  • GS_008
  • GS_008
  • 2016年04月29日 00:37
  • 1028

强类型语言和弱类型语言

编译型和解释型 我们先看看编译型,其实它和汇编语言是一样的:也是有一个负责翻译的程序来对我们的源代码进行转换,生成相对应的可执行代码。这个过程说得专业一点,就称为编译(Compile),而负...
  • sinolzeng
  • sinolzeng
  • 2014年11月03日 16:30
  • 5613

弱类型、强类型、动态类型、静态类型语言的区别是什么?

原文:http://www.zhihu.com/question/19918532 类型系统的一些概念,众说纷纭,使用上也比较乱。有些东西,甚至不好严格定义。以下算学术界的一种相对“严格”的...
  • swgshj
  • swgshj
  • 2015年07月17日 10:43
  • 917

强类型和弱类型的区别---非正确版

强类型:为所有变量指定数据类型称为“强类型”。 强/弱类型是指类型检查的严格程度的。语言有无类型,弱类型和强类型三种。无类型的不检查,甚至不区分指令和数据。弱类型的检查很弱,仅能严格的区分指令和数据...
  • cjf1002361126
  • cjf1002361126
  • 2016年10月07日 19:32
  • 2701

强类型语言JAVA与弱类型语言JS的小小认识

从servlet的原理说起,我们知道servlet是不能独立运行的,是需要配合服务器(servlet容器,tomcat之类的)来组合成一个独立的应用。也就是说servlet对象是不被servlet实现...
  • bianhuacx
  • bianhuacx
  • 2015年10月30日 17:29
  • 979

c# 中的泛型以及强类型与弱类型

一、泛型的概念 (1)没有泛型的时候,所有的对象都是以object为基础(object是所有对象的基类),如果要使用时必须进行强制类型转换。对于值类型的转换,则会导致不断拆箱、装箱的过程,会造成系统...
  • ydm19891101
  • ydm19891101
  • 2015年05月04日 15:40
  • 2194

编译型与解释型、动态语言与静态语言、强类型语言与弱类型语言的区别

译型和解释型。  我们先看看编译型,其实它和汇编语言是一样的:也是有一个负责翻译的程序来对我们的源代码进行转换,生成相对应的可执行代码。这个过程说得专业一点,就称为编译(Compile),而负责...
  • ysj_love
  • ysj_love
  • 2016年03月24日 14:39
  • 1505

关于OC语言基础的总结

原文地址:http://www.kankanews.com/ICkengine/archives/24423.shtml
  • hengshujiyi
  • hengshujiyi
  • 2014年10月31日 17:04
  • 3309

JavaScript 弱类型浅谈

1,强弱类型的判别;           按照计算机语言的类型系统的设计方式,可以分为强类型和弱类型两种。二者之间的区别,就在于计算时是否可以不同类型之间对使用者透明地隐式转换。从使用者的角度来看,...
  • GitMind
  • GitMind
  • 2016年03月15日 11:58
  • 3294
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:强类型、弱类型与动态类型
举报原因:
原因补充:

(最多只允许输入30个字)