python 强类型 弱类型_强类型、弱类型与动态类型 (转)

", 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 weblogs/viewpost.JSP?thread=7590#poly">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.

Discussions of types

Bruce Eckel and Python's weak typing

Artima Interview: Type Checking and TechieControl

http://www.artima.com/intv/typing.html

Strong Typing vs. Strong Testing

.NET/WebLog/log-0025">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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值