Python 的 class attributes 和 instance attributes 的区别
2015-11-07 13:30
597 查看
上一篇博文提到,attribute 分为类属性和数据属性,还没有搞懂。紧接着就用 Google 搜索到了详细的介绍(话说 bing 虽然比 baidu强一些,但还是不够给力。万恶的GFW[怒])http://www.cnblogs.com/wilber2013/p/4677412.html
原来不是 date attributes,而是 instance date attributes. 用文章中的一段代码来说明就清楚了:
用 CodeSkulptor 简单改了改,显示结果如下:
知识点:
1、Student.hobby 没有预先在 Class 中定义,但可以直接调用类名创建并赋值;
2、Wilber.gender 也是同样的道理,但 Student.hobby 是 Class attribute,而 Wilber.gender 是 Instance attribute,所以这里是直接调用实例名创建并赋值。
3、但 instance attribute 仅由该 instance 所拥有,所以我们也可以看到
4、同样的,新建的Instance will 也不存在 gender 属性
5、一个有意思的现象是,在 CodeSkulptor 里面,虽然新建了 Student.hobby, 但其并不存在于Instance当中。而原作者@田小计划 的运行结果却不同(见下图)。这可能是因为CodeSkulptor是基于Python 2.x的原因吧。以后得自己安装Python环境了。
原来不是 date attributes,而是 instance date attributes. 用文章中的一段代码来说明就清楚了:
class Student(object): count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age pass Student.books.extend(["python", "javascript"]) print "Student book list: ", Student.books # class can add class attribute after class defination Student.hobbies = ["reading", "jogging", "swimming"] print "Student hobby list: ", Student.hobbies print "Student's attributes: " print dir(Student) print wilber = Student("Wilber", 28) print "%s is %d years old" %(wilber.name, wilber.age) # class instance can add new attribute # "gender" is the instance attribute only belongs to wilber wilber.gender = "male" print "%s is %s" %(wilber.name, wilber.gender) # class instance can access class attribute print "wilber's attributes: " print dir(wilber) print "Student's attributes: " print dir(Student) wilber.books.append("C#") print wilber.books print will = Student("Will", 27) print "%s is %d years old" %(will.name, will.age) # will shares the same class attribute with wilber # will don't have the "gender" attribute that belongs to wilber print "will's attributes: " print dir(will) print will.books
用 CodeSkulptor 简单改了改,显示结果如下:
知识点:
1、Student.hobby 没有预先在 Class 中定义,但可以直接调用类名创建并赋值;
2、Wilber.gender 也是同样的道理,但 Student.hobby 是 Class attribute,而 Wilber.gender 是 Instance attribute,所以这里是直接调用实例名创建并赋值。
3、但 instance attribute 仅由该 instance 所拥有,所以我们也可以看到
dir(wilber)和
dir(Student)的结果不一样,wilber 拥有 gender 属性,但是在 Student类中,却并不存在 gender 属性
4、同样的,新建的Instance will 也不存在 gender 属性
5、一个有意思的现象是,在 CodeSkulptor 里面,虽然新建了 Student.hobby, 但其并不存在于Instance当中。而原作者@田小计划 的运行结果却不同(见下图)。这可能是因为CodeSkulptor是基于Python 2.x的原因吧。以后得自己安装Python环境了。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法