search
HomeBackend DevelopmentPython Tutorialpython动态性强类型用法实例

本文实例分析了python动态性强类型用法。分享给大家供大家参考。具体如下:

Python变量声明和定义

与C#不同,Python在使用变量之前无须定义它的类型,试着运行下面的例子:

i = 12 print i

从上边我们可以看到,变量 i 在使用前并不需要定义,但是必须声明以及初始化该变量。试着运行下面的例子:

i = 1
print i + j

上面的代码会产生一个异常:“NameError: name 'j' is not defined”,Python提示变量 j 没有定义。这点和BASIC等弱类型的语言不一样。在BASIC中,执行上述代码的时候不会产生异常,你可以在EXCEL的VBA开发环境里试一下,把 print改为MsgBox就可以,结果会输出 1 。这说明Python并不是一种类似BASIC的弱类型语言。

另一方面,Python与C#有一个很大的差异就是在程序运行过程中,同一变量名可以(在不同阶段)代表不同类型的数据,看看下边的例子:

i = 1
print i,type(i),id(i)
i = 10000000000
print i,type(i),id(i)
i = 1.1
print i,type(i),id(i)

变量 i 的类型在程序执行过程中分别经历了int、long和float的变化,这和静态类型语言(如C等)有很大不同。静态语言只要一个变量获得了一个数据类 型,它就会一直是这个类型,变量名代表的是用来存放数据的内存位置。而Python中使用的变量名只是各种数据及对象的引用,用id()获取的才是存放数 据的内存位置,我们输入的1、10000000000和1.1三个数据均会保存在id()所指示的这些内存位置中,直到垃圾回收车把它拉走(在系统确定你 不再使用它的时候)。这是动态语言的典型特征,它确定一个变量的类型是在给它赋值的时候。

另一方面,Python又是强类型的,试着运行下边的例子:

# -*- coding: utf-8 -*-
i = 10; j = 'ss'
print i+j
#正确的写法是print str(i)+j,输出10ss

会产生一个异常:“TypeError: unsupported operand type(s) for +: 'int' and 'str'”。在BASIC等弱类型的语言中,上边的例子会正常运行并返回(虽然有时候是不可预期的)结果。

所以,我们说Python既是一种动态类型语言,同时也是一种强类型的语言,这点是和C#不同的地方。对于Python的这种变量的声明、定义和使 用方式,C#程序员可能要花一段时间去适应,不过相信你会很快就喜欢上它,因为它让事情变得更加简单(而且不会不安全)。而且,C# 4.0 已经开始用类似的方式定义和使用变量(通过在变量名前加关键字dynamic),如果你先学了Python变量,将能够更快的适应C# 4.0的动态编程特征。

希望本文所述对大家的Python程序设计有所帮助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Merging Lists in Python: Choosing the Right MethodMerging Lists in Python: Choosing the Right MethodMay 14, 2025 am 12:11 AM

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

How to concatenate two lists in python 3?How to concatenate two lists in python 3?May 14, 2025 am 12:09 AM

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Python concatenate list stringsPython concatenate list stringsMay 14, 2025 am 12:08 AM

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

Python execution, what is that?Python execution, what is that?May 14, 2025 am 12:06 AM

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Python: what are the key featuresPython: what are the key featuresMay 14, 2025 am 12:02 AM

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python: compiler or Interpreter?Python: compiler or Interpreter?May 13, 2025 am 12:10 AM

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Python For Loop vs While Loop: When to Use Which?Python For Loop vs While Loop: When to Use Which?May 13, 2025 am 12:07 AM

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Python loops: The most common errorsPython loops: The most common errorsMay 13, 2025 am 12:07 AM

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),