与一些传言不同,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 "<stdin>", 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'
</stdin>
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.
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.
分享到:
相关推荐
python 学习中关于动态类型静态类型强类型弱类型的问题
5.5游标强类型弱类型异常报错.sql
PYTHON是一门动态解释性的强类型定义语言:编写时无需定义变量类型;运行时变量类型强制固定;无需编译,在解释器环境直接运行。 动态和静态 静态语言:是指在编译时变量的数据类型即可确定的语言,多数静态类型语言...
主要介绍了动态语言、动态类型语言、静态类型语言、强类型语言、弱类型语言介绍,需要的朋友可以参考下
一种强化javascript的弱类型的方法,王磊,,随着javascript引擎技术的日益成熟以及JIT即时编译技术的完善,javascript作为一门脚本语言大量
主要介绍了编程语言里的静态、动态、强类型、弱类型等概念介绍,需要的朋友可以参考下
1、强类型局部更新刷新,只能用于基于浏览器的渲染显示;强类型局部更新刷新,需要使用“PartialView”方法实现。...2、弱类型局部更新刷新,即能用于基于浏览器的渲染显示,也能用于App更新刷新,
自己网上总结的,大部分是自己从网上搜索总结,当然有些非常好的就直接复制粘贴,因为查询太多的文章,这里就不写出参考文章地址了,使用EditPlus观看更佳,记事本就没有好格式了
Any2Dto插件,可以根据数据库和JavaCode生成强类型且精确... 从而避免了代码中的复制和赋值问题,也避免了map和反射等弱类型和动态弊端。在高质量的敏捷开发中,强类型和限制使用,是代码重构和数据模型变更的有利保证
c和c++是静态语言,也是弱类型语言,perl和php是动态语言,但也是弱类型语言,强类型语言在没有强制类型转换前,不允许两种不同类型的变量相互操作。java、c#和python都是强类型语言。 使用那种语言还是要按需而定。...
背景强类型与弱类型js 动态弱类型语言。TypeScript 不是强类型!只是静态类型!快速入门 TypeScriptnpm install -g typesc
本文实例分析了python动态性强类型用法。分享给大家供大家参考。具体如下: Python变量声明和定义 与C#不同,Python在使用变量之前无须定义它的类型,试着运行下面的例子: i = 12 print i 从上边我们可以看到,...
鳟鱼脚本用javascript编写的经过编译的强类型脚本语言。 这是我第一次(真正)尝试编写一种完整的编程语言。 在此过程中,我学到了很多东西,最终将使它变得稳定并清理所有内容。特征严格类型的变量Javascript中的...
弱类型语言也称为弱类型定义语言。与强类型定义相反。像vb,php等就属于弱类型语言,这篇文章给大家详细介绍关于PHP弱类型的安全问题,有需要的可以参考借鉴,下面来一起看看吧。
# javascript:是一门动态的弱类型语言,运行时识别数据类型 字符串(str) # 单引号和双引号 temp = 'hello python' temp = "hello python" print(temp) # 转义符处理 temp="I say \"hello world\...
转成数字对象:强类型、显示转换:强制转换成数字类型。Number() 隐式型、弱类型转换:+ - * / (运算符) undefined 转数字:NaN null 转成数字:0 true 转数字:1 false 转成数字:0 数字除以0结果是infinity...
它和Java不一样,它是动态语言,解释型语言,弱数据类型《无需声明》,赋值的内容是什么类型,左边的变量就是什么类型 虽然他是不需要提前声明类型,但是它也有数据类型。 (2)Python中的赋值 简单赋值:例如:...
说明:虽然python声明变量时没有一个类型来圈注,但它并不是弱类型语言,相反,它是一门强类型语言。 弱类型的语言的东西没有明显的类型,它能随着环境的不同自动变换类型; 而强类型则没这样的规定,不同类型间的...
3、统一的接口:强类型、弱类型采用统一的数据库接口,例如:可以采用统一的insert方法报错强类型或弱类型数据。4、数据库的支持:目前已经支持MySql、SqlServer、Oracle数据库,屏蔽了数据库的语法差异。5、强弱...