`
ihuashao
  • 浏览: 4725393 次
  • 性别: Icon_minigender_1
  • 来自: 济南
社区版块
存档分类
最新评论

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

阅读更多
与一些传言不同,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'
&gt;&gt;&gt; 1 + 1
2
&gt;&gt;&gt; "1" + "1"
'11'
&gt;&gt;&gt; 1 + int("1")
2
&gt;&gt;&gt; "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 学习中关于动态类型静态类型强类型弱类型的问题.docx

    ### Python学习中关于动态类型、静态类型、强类型与弱类型的问题 #### 动态类型与静态类型 在计算机编程领域,动态类型和静态类型是两种重要的类型系统分类方式。 **动态类型**(Dynamic Typing)指的是在程序...

    弱类型语言允许将一块内存看做多种类型

    - **Python**:虽然 Python 在表面上看起来是弱类型语言,因为它支持动态类型,但实际上在操作不同类型的数据时仍然需要遵循严格的规则,因此被视为强类型语言。 ### Java 中 WeakHashMap 的使用及特性 #### 五、...

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

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

    5.5游标强类型弱类型异常报错.sql

    5.5游标强类型弱类型异常报错.sql

    动态语言、动态类型语言、静态类型语言、强类型语言、弱类型语言介绍

    本文将深入探讨动态语言、动态类型语言、静态类型语言、强类型语言和弱类型语言的区别,帮助理解它们各自的特点。 1. 动态语言: 动态语言,也被称为动态编程语言,其核心特征是在运行时允许程序结构的变化。这意味...

    Python动态强类型解释型语言原理解析

    PYTHON是一门动态解释性的强类型定义语言:编写时无需定义变量类型;运行时变量类型强制固定;无需编译,在解释器环境直接运行。 动态和静态 静态语言:是指在编译时变量的数据类型即可确定的语言,多数静态类型语言...

    linq to datasets,通过linq访问强类型数据集

    - 将这些类与DataSet关联,形成强类型数据集。 **4. LINQ查询的基本结构** 查询表达式由关键字`from`、`where`、`select`等构成,例如: ```csharp var query = from customer in Customers where customer.City ...

    编程语言里的静态、动态、强类型、弱类型等概念介绍

    值得一提的是,随着编程语言的发展,现代的编程语言往往融合了静态类型与动态类型、强类型与弱类型的特点。例如,Python虽然属于动态类型语言,但其3.x版本引入了类型注解,增强了类型的可选静态特性。JavaScript在...

    221025-13Linkage(局部刷新的强类型实现)

    与强类型局部刷新不同,弱类型更新不强制模型数据类型,这使得它更加灵活,可以应用于基于浏览器的渲染以及App更新刷新。在某些情况下,如使用JavaScript或者jQuery的Ajax请求更新页面部分,我们可能无法提供强类型...

    Java中的引用类型详解:强引用、软引用、弱引用与虚引用

    从JDK 1.2版本开始,Java引入了四种不同级别的引用:强引用(Strong Reference)、软引用(Soft Reference)、弱引用(Weak Reference)和虚引用(Phantom Reference)。这些引用类型提供了灵活的内存管理策略,允许...

    python动态性强类型用法实例

    本文将详细介绍Python中动态性强类型的具体用法,并通过与C#的对比来加深理解。 #### 二、Python变量声明与定义 在Python中,变量的声明和定义非常灵活。与C#等静态类型语言不同,Python无需在使用变量前明确指定...

    DynamicDataRecord:将 IDataReaderIDataRecord 动态转换为适合序列化的强类型类的类库

    然而,这些接口返回的数据通常是弱类型的,这意味着你需要通过索引或字段名来访问数据,这在进行序列化或与强类型对象交互时可能会变得复杂。`DynamicDataRecord`项目就是为了简化这一过程,它将`IDataReader`或`...

    编译型_解释型_强类型_弱类型_脚本.txt

    自己网上总结的,大部分是自己从网上搜索总结,当然有些非常好的就直接复制粘贴,因为查询太多的文章,这里就不写出参考文章地址了,使用EditPlus观看更佳,记事本就没有好格式了

    20-T20:php弱类型.zip

    这是向强类型系统迈进的一步,但PHP仍然保持其整体的弱类型特性。 7. **错误处理**:由于弱类型可能导致意外行为,开发过程中应格外注意类型检查。使用`is_*`函数(如`is_int()`, `is_string()`)或`gettype()`可以...

    Any2Dto插件,可以根据数据库和JavaCode生成强类型且精确字段的DTO

    Any2Dto插件,可以根据数据库和JavaCode生成强类型且精确... 从而避免了代码中的复制和赋值问题,也避免了map和反射等弱类型和动态弊端。在高质量的敏捷开发中,强类型和限制使用,是代码重构和数据模型变更的有利保证

    php中的类型约束类库

    虽然PHP是一种弱类型的语言,但它自PHP 7开始引入了更强的类型提示(type hints)来增强类型安全。在PHP中,类型约束主要体现在以下几个方面: 1. 类型提示:这是PHP中最早引入的类型约束形式,允许开发者在函数或...

    trout-script:用JavaScript编写的经过编译的强类型脚本语言

    鳟鱼脚本用javascript编写的经过编译的强类型脚本语言。 这是我第一次(真正)尝试编写一种完整的编程语言。 在此过程中,我学到了很多东西,最终将使它变得稳定并清理所有内容。特征严格类型的变量Javascript中的...

    .NET面试题C#.NET

    c和c++是静态语言,也是弱类型语言,perl和php是动态语言,但也是弱类型语言,强类型语言在没有强制类型转换前,不允许两种不同类型的变量相互操作。java、c#和python都是强类型语言。 使用那种语言还是要按需而定。...

    liukexina#weekly#2020-35周-cy-typescript基本类型1

    背景强类型与弱类型js 动态弱类型语言。TypeScript 不是强类型!只是静态类型!快速入门 TypeScriptnpm install -g typesc

Global site tag (gtag.js) - Google Analytics