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

----来自维基百科

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

  1. >>> class Person():
  2. def __init__(self, name = None, age = None):
  3. self.name = name
  4. self.age = age
  5. >>> P = Person("The_Third_Wave", "24")
  6. >>>

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

  1. >>> P.sexuality = "male"
  2. >>> P.sexuality
  3. 'male'
  4. >>>

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

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

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

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

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

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

  1. >>>> Person.sexuality = None
  2. >>> P1 = Person("Wave", "25")
  3. >>> print P1.sexuality
  4. None
  5. >>>

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

那么function呢?怎么绑定?

  1. >>> class Person():
  2. def __init__(self, name = None, age = None):
  3. self.name = name
  4. self.age = age
  5. def eat(self):
  6. print "eat food"
  7. >>> def run(self, speed):
  8. print "Keeping moving, the speed is %s km/h" %speed
  9. >>> P = Person("The_Third_Wave", "24")
  10. >>>
  11. KeyboardInterrupt
  12. >>> P.run()
  13. Traceback (most recent call last):
  14. File "<pyshell#5>", line 1, in <module>
  15. P.run()
  16. AttributeError: Person instance has no attribute 'run'
  17. >>> P.eat()
  18. eat food
  19. >>> import types
  20. >>> Person.run = types.MethodType(run, None, Person)
  21. >>> P.run(180)
  22. Keeping moving, the speed is 180 km/h
  23. >>>

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

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

  1. >>> P.name
  2. 'The_Third_Wave'
  3. >>> P.sex
  4. Traceback (most recent call last):
  5. File "<pyshell#32>", line 1, in <module>
  6. P.sex
  7. AttributeError: Person instance has no attribute 'sex'
  8. >>> setattr(P, "sex", "male") # 増
  9. >>> P.sex
  10. 'male'
  11. >>> delattr(P, "name") # 删
  12. >>> P.name
  13. Traceback (most recent call last):
  14. File "<pyshell#36>", line 1, in <module>
  15. P.name
  16. AttributeError: Person instance has no attribute 'name'
  17. >>>

加入方法呢?

  1. >>> class Person():
  2. def __init__(self, name = None, age = None):
  3. self.name = name
  4. self.age = age
  5. def eat(self):
  6. print "eat food"
  7. >>> P = Person("The_Third_Wave", "24")
  8. >>> P.eat()
  9. eat food
  10. >>> P.run()
  11. Traceback (most recent call last):
  12. File "<pyshell#41>", line 1, in <module>
  13. P.run()
  14. AttributeError: Person instance has no attribute 'run'
  15. >>> def run(self, speed):
  16. print "Keeping moving, the speed is %s" %speed
  17. >>> setattr(P, "run", run)
  18. >>> P.run(360)
  19. Traceback (most recent call last):
  20. File "<pyshell#45>", line 1, in <module>
  21. P.run(360)
  22. TypeError: run() takes exactly 2 arguments (1 given)
  23. >>> P.run(1, 360)
  24. Keeping moving, the speed is 360
  25. >>>

删除

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

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

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

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

  1. >>> class Person():
  2. __slots__ = ("location", "run")
  3. def __init__(self, name = None, age = None):
  4. self.name = name
  5. self.age = age
  6. def eat(self):
  7. print "eat food"
  8. >>> P = Person()
  9. >>> P.sex
  10. Traceback (most recent call last):
  11. File "<pyshell#3>", line 1, in <module>
  12. P.sex
  13. AttributeError: Person instance has no attribute 'sex'
  14. >>> P.sex = "male"
  15. >>>

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

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

这可真是个神坑!soga!

  1. >>> class Person(object):
  2. __slots__ = ("location", "run")
  3. def __init__(self, name = None, age = None):
  4. self.name = name
  5. self.age = age
  6. def eat(self):
  7. print "eat food"
  8. >>> P = Person()
  9. Traceback (most recent call last):
  10. File "<pyshell#12>", line 1, in <module>
  11. P = Person()
  12. File "<pyshell#11>", line 5, in __init__
  13. self.name = name
  14. AttributeError: 'Person' object has no attribute 'name' # 顺便还发现了个注意事项:要预先定义的属性也要写到tuple里面!
  15. >>> class Person(object):
  16. __slots__ = ("name", "age", "eat", "location", "run")
  17. def __init__(self, name = None, age = None):
  18. self.name = name
  19. self.age = age
  20. def eat(self):
  21. print "eat food"
  22. >>> P = Person()
  23. >>> P.sex = "male"
  24. Traceback (most recent call last):
  25. File "<pyshell#16>", line 1, in <module>
  26. P.sex = "male"
  27. AttributeError: 'Person' object has no attribute 'sex'
  28. >>> P.location = "china"
  29. >>> P.location
  30. 'china'
  31. >>> def run(self, speed):
  32. print "Keeping moving, the speed is %s km/h" %speed
  33. >>> setattr(P, "run", run)
  34. >>> P.run(u"请注意这儿參数和上面有个样例不一样哦", 720)
  35. Keeping moving, the speed is 720 km/h
  36. >>>

顺便还发现了个注意事项:要预先定义的属性也要写到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. gitlab gitlab runner

    1.安装gitlab https://about.gitlab.com/installation/#ubuntu 2.安装runner https://docs.gitlab.com/runner/i ...

  2. How to convert .crt to .pem [duplicate]证书转化

    openssl x509 -in mycert.crt -out mycert.pem -outform PEM openssl x509 -inform DER -in yourdownloaded ...

  3. SilverLight-Access:银光项目测试数据类列表

    ylbtech-SilverLight-Access:银光项目测试数据类列表 1.A, Product.cs 产品类 1.A, Product.cs 产品类返回顶部 1,/Access/Product ...

  4. 关于Web项目的pom文件处理

    pom文件的方式需要修改的是 <packaging>war</packaging> <profiles> <profile> <id>com ...

  5. ArcGIS教程:面积制表

    摘要 计算两个数据集之间交叉制表的区域并输出表. 插图 使用方法 · 区域定义为输入中具有同样值的全部区.各区无需相连. 栅格和要素数据集都可用于区域输入. · 假设区域输入和类输入均为具有同样分辨率 ...

  6. leetcode 46-Permutations and 47-Permutations II

    Permutations Given a collection of numbers, return all possible permutations. For example, [1,2,3] h ...

  7. 利用window.navigator.userAgent判断当前是否微信内置浏览器

    <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8&quo ...

  8. Android · PendingIntent学习

    Intent 是及时启动,intent 随所在的activity 消失而消失 PendingIntent用于处理即将发生的事情.比如在通知Notification中用于跳转页面,但不是马上跳转.   ...

  9. Nook 2 Root

        最后我还是忍不住root了它,用了差一点够一个月 1.备份2.root 3.装软件=====================================================1. ...

  10. STM32单片机和51单片机区别

    单片机 / AVR / PIC / STM32 / 8051803189C5189S51 6905 单片机简介 单片微型计算机简称单片机,简单来说就是集CPU(运算.控制).RAM(数据存储-内存). ...