动态语言的定义:动态编程语言是高级程序设计语言的一个类别。在计算机科学领域已被广泛应用。它是一类在执行时能够改变其结构的语言:比如新的函数、对象、甚至代码能够被引进。已有的函数能够被删除或是其它结构上的变化。动态语言眼下很具有活力。众所周知的ECMAScriptJavaScript)便是一个动态语言,除此之外如PHPRubyPython等也都属于动态语言,而CC++等语言则不属于动态语言。

----来自维基百科

你是不是有过给class里面变量赋值却发现程序没达到自己预期结果的遭遇?是不是本来赋值给class.abc却赋给了class.abd?这事实上是动态语言惹的“祸”!【博主曾经玩的是java】我们先来试着玩一玩

>>> class Person():
def __init__(self, name = None, age = None):
self.name = name
self.age = age >>> P = Person("The_Third_Wave", "24")
>>>

在这里。我们定义了1个类Person。在这个类里。定义了两个初始属性name和age,可是人还有性别啊。假设这个类不是你写的是不是你会尝试訪问性别这个属性呢?

>>> P.sexuality = "male"
>>> P.sexuality
'male'
>>>

这时候就发现问题了,我们定义的类里面没有sexuality这个属性啊!

怎么回事呢?这就是动态语言的魅力和坑!

这里实际上就是动态给实例绑定属性!所以博主“当年”从java转python被“坑”(无知啊)过!我们再看下一个样例

>>> P1 = Person("Wave", "25")
>>> P1.sexuality Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
P1.sexuality
AttributeError: Person instance has no attribute 'sexuality'
>>>

我们尝试打印P1.sexuality,发现报错,P1没有sexuality这个属性。----给P这个实例绑定属性对P1这个实例不起作用。

那我们要给全部的Person的实例加上sexuality属性怎么办呢?答案就是直接给Person绑定属性!

>>>> Person.sexuality = None
>>> P1 = Person("Wave", "25")
>>> print P1.sexuality
None
>>>

我们直接给Person绑定sexuality这个属性,重行实例化P1后。P1就有sexuality这个属性了!

那么function呢?怎么绑定?

>>> class Person():
def __init__(self, name = None, age = None):
self.name = name
self.age = age
def eat(self):
print "eat food" >>> def run(self, speed):
print "Keeping moving, the speed is %s km/h" %speed >>> P = Person("The_Third_Wave", "24")
>>>
KeyboardInterrupt
>>> P.run() Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
P.run()
AttributeError: Person instance has no attribute 'run'
>>> P.eat()
eat food
>>> import types
>>> Person.run = types.MethodType(run, None, Person)
>>> P.run(180)
Keeping moving, the speed is 180 km/h
>>>

绑定我们了解了,可是怎么删除呢?

请看下面样例首先给的是属性的真删:

>>> P.name
'The_Third_Wave'
>>> P.sex Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
P.sex
AttributeError: Person instance has no attribute 'sex'
>>> setattr(P, "sex", "male") # 増
>>> P.sex
'male'
>>> delattr(P, "name") # 删
>>> P.name Traceback (most recent call last):
File "<pyshell#36>", line 1, in <module>
P.name
AttributeError: Person instance has no attribute 'name'
>>>

加入方法呢?

>>> class Person():
def __init__(self, name = None, age = None):
self.name = name
self.age = age
def eat(self):
print "eat food" >>> P = Person("The_Third_Wave", "24")
>>> P.eat()
eat food
>>> P.run() Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
P.run()
AttributeError: Person instance has no attribute 'run'
>>> def run(self, speed):
print "Keeping moving, the speed is %s" %speed >>> setattr(P, "run", run)
>>> P.run(360) Traceback (most recent call last):
File "<pyshell#45>", line 1, in <module>
P.run(360)
TypeError: run() takes exactly 2 arguments (1 given)
>>> P.run(1, 360)
Keeping moving, the speed is 360
>>>

删除

>>> delattr(P, "run")
>>> P.run() Traceback (most recent call last):
File "<pyshell#48>", line 1, in <module>
P.run()
AttributeError: Person instance has no attribute 'run'
>>>

通过以上样例能够得出一个结论:相对于动态语言,静态语言具有严谨性!

所以。玩动态语言的时候,小心动态的坑!

那么怎么避免这样的情况呢?请使用__slots__。可是我的是2.7.6版本号,測试是不行的。代码例如以下:

>>> class Person():
__slots__ = ("location", "run") def __init__(self, name = None, age = None):
self.name = name
self.age = age def eat(self):
print "eat food" >>> P = Person()
>>> P.sex Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
P.sex
AttributeError: Person instance has no attribute 'sex'
>>> P.sex = "male"
>>>

详细原因是什么呢,本来是准备请等待更新:ing...的

BUT。我多写了个object就出来了。。。

这可真是个神坑!soga!

>>> class Person(object):
__slots__ = ("location", "run") def __init__(self, name = None, age = None):
self.name = name
self.age = age def eat(self):
print "eat food" >>> P = Person() Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
P = Person()
File "<pyshell#11>", line 5, in __init__
self.name = name
AttributeError: 'Person' object has no attribute 'name' # 顺便还发现了个注意事项:要预先定义的属性也要写到tuple里面! >>> class Person(object):
__slots__ = ("name", "age", "eat", "location", "run") def __init__(self, name = None, age = None):
self.name = name
self.age = age def eat(self):
print "eat food" >>> P = Person()
>>> P.sex = "male" Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
P.sex = "male"
AttributeError: 'Person' object has no attribute 'sex'
>>> P.location = "china"
>>> P.location
'china'
>>> def run(self, speed):
print "Keeping moving, the speed is %s km/h" %speed >>> setattr(P, "run", run)
>>> P.run(u"请注意这儿參数和上面有个样例不一样哦", 720)
Keeping moving, the speed is 720 km/h
>>>

顺便还发现了个注意事项:要预先定义的属性也要写到tuple里面!

临时写到这,不定期更新ing...

关于slots的demo原文:https://docs.python.org/2/reference/datamodel.html?

highlight=__slots__#__slots__

本文由@The_Third_Wave原创。不定期更新。有错误请指正。

Sina微博关注:@The_Third_Wave 

假设这篇博文对您有帮助,为了好的网络环境,不建议转载,建议收藏!假设您一定要转载。请带上后缀和本文地址。

为什么说Python是一门动态语言--Python的魅力的更多相关文章

  1. python基础实践 -python是一门动态解释性的强类型定义语言

    python是一门动态解释性的强类型定义语言 Python能做什么? Python是一门综合性的语言,你几乎能在计算机上通过Python做任何事情,以下是Python应该最广泛的几个方面: 1.网络应 ...

  2. python是一门解释性语言吗?

    其实这只能算说对了一半,准确来说是编译跟解释性语言.python跟java.C# 一样都是会预编译一部分代码(简称做了优化) 都知道java编译要先在cmd里敲 javac hello.world 是 ...

  3. 【程序员技术练级】学习一门脚本语言 python(一)文件处理

    现在工作上主要用的语言是java,java在企业级的应用上能够发挥很好的用途,但有时候要做一个小功能时,比如批量更新文件,抓取网页等,这时候用java就显得太笨重了.因此就学习了python这门脚本语 ...

  4. 【程序员技术练级】学习一门脚本语言 python(三)跟数据库打交道

    接着上一篇,该篇讲述使用python对数据库进行基本的CRUD操作,这边以sqlite3为例子,进行说明.sqlite3 是一个非常轻型的数据库,安装和使用它是非常简单的,这边就不进行讲述了. 在py ...

  5. 【程序员技术练级】学习一门脚本语言 python(二)遍历本地文件系统

    这篇将讲述怎么使用python来遍历本地文件系统,并把文件按文件大小从小到大排序的一个小例子 在这个例子中,主要会用到python内置的和OS模块的几个函数: os.walk() : 该方法用来遍历指 ...

  6. Python 笔试集(3):编译/解释?动态/静态?强/弱?Python 是一门怎样的语言

    面试题 解释/编译?动态/静态?强/弱?Python 到底是一门怎样的语言? 编译 or 解释? 编译.解释都是指将(与人类亲和的)编程语言翻译成(计算机能够理解的)机器语言(Machine code ...

  7. Python是一门什么样的语言

    先做个总结:Python是一门动态解释型的强类型定义语言. 那何为动态?何为解释?何为强类型呢? 我们需要了解编译型和解释型.静态语言和动态语言.强类型定义语言和弱类型定义语言这6个概念就可知晓. 编 ...

  8. 动态语言的灵活性是把双刃剑 -- 以Python语言为例

    本文有些零碎,总题来说,包括两个问题:(1)可变对象(最常见的是list dict)被意外修改的问题,(2)对参数(parameter)的检查问题.这两个问题,本质都是因为动态语言(动态类型语言)的特 ...

  9. 动态语言的灵活性是把双刃剑 -- 以 Python 语言为例

    本文有些零碎,总题来说,包括两个问题:(1)可变对象(最常见的是list dict)被意外修改的问题,(2)对参数(parameter)的检查问题.这两个问题,本质都是因为动态语言(动态类型语言)的特 ...

随机推荐

  1. Java Servlet Filter

    做web开发的人对于Filter应该不会陌生,一直在很简单的使用,但是一直没有系统的总结一下,随着年纪的慢慢长大,喜欢总结一些事情,下面说说我对Filter的理解,官方给出的Filter的定义是在请求 ...

  2. Jenkins错误“to depth infinity with ignoreexternals:true”问题解决

    试下以下解决方法: 1.可能是SVN插件版本过低导致,升级SVN插件. 2.可能是构建时自己手动修改了代码,而SVN检出时无法覆盖导致的错误,可以先删除jenkins检出的代码,然后再检出一次去构建. ...

  3. php数据库操作代码

    数据库名为reg,表名为member,字段名为username,password,regdate <?php $link=@mysql_connect("localhost" ...

  4. OpenCV3.1使用SIFT

    待完善... Opencv3.1.0+opencv_contrib配置及使用SIFT测试

  5. 测试整合之王Unitils

    16.4.1  Unitils概述(1) Unitils测试框架目的是让单元测试变得更加容易和可维护.Unitils构建在DbUnit与EasyMock项目之上并与JUnit和TestNG相结合.支持 ...

  6. POJ 3181 Dollar Dayz(全然背包+简单高精度加法)

    POJ 3181 Dollar Dayz(全然背包+简单高精度加法) id=3181">http://poj.org/problem?id=3181 题意: 给你K种硬币,每种硬币各自 ...

  7. Android开发之布局文件里实现OnClick事件关联处理方法

    一般监听OnClickListener事件,我们都是通过Button button = (Button)findViewById(....); button.setOClickLisener....这 ...

  8. vue 组件创建与销毁

    vue 组件(如对话框组件)实时创建与销毁: 使用v-if <search-history :show="showSearchHistory" @close="sh ...

  9. bzoj1061【NOI2008】志愿者招募

    1061: [Noi2008]志愿者招募 Time Limit: 20 Sec  Memory Limit: 162 MB Submit: 2740  Solved: 1703 [Submit][id ...

  10. OLR

    OLR:Oracle Local Registry 环境:11.2.0.3  RAC  RHEL6.5 It contains local node specific configuration re ...