Python 的 class attributes 和 instance attributes 的区别
来源:互联网 发布:gap淘宝旗舰店可靠吗 编辑:程序博客网 时间:2024/05/18 00:43
上一篇博文提到,attribute 分为类属性和数据属性,还没有搞懂。紧接着就用 Google 搜索到了详细的介绍(话说 bing 虽然比 baidu强一些,但还是不够给力。万恶的GFW[怒])http://www.cnblogs.com/wilber2013/p/4677412.html
原来不是 date attributes,而是 instance date attributes. 用文章中的一段代码来说明就清楚了:
class Student(object): count = 0 books = [] def __init__(self, name, age): self.name = name self.age = age passStudent.books.extend(["python", "javascript"]) print "Student book list: ", Student.books # class can add class attribute after class definationStudent.hobbies = ["reading", "jogging", "swimming"]print "Student hobby list: ", Student.hobbiesprint "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 wilberwilber.gender = "male"print "%s is %s" %(wilber.name, wilber.gender) # class instance can access class attributeprint "wilber's attributes: "print dir(wilber)print "Student's attributes: "print dir(Student)wilber.books.append("C#")print wilber.booksprint 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 wilberprint "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 的 class attributes 和 instance attributes 的区别
- R:attr()和attributes()的区别
- @property (attributes) 迷惑的attributes
- Interface Attributes != Class Attributes
- jquery中.prop()和.attr()的区别 什么叫布尔型属性 property vs attributes , boolean attributes...
- NUnit的常用Attributes
- label的attributes相关
- Attributes的使用
- Attributes的NSDctionary设置
- 我的特性Attributes
- Attributes
- Attributes
- $$Attributes
- jquery的tree的attributes
- button控件的.Attributes属性
- 关于Attributes属性的介绍
- C#中Attributes的用法
- C#中 Attributes的用法
- 朋友,不是乞讨来的
- iOS(8+)扩展之活动(PS.把自己的应用添加到活动)
- 制作C#项目安装包
- c_rehash
- HDU---4333-Revolving Digits(扩展KMP)
- Python 的 class attributes 和 instance attributes 的区别
- objective-C:Day3~Day4
- 虚拟机的使用
- codeforces-559B-Equivalent Strings
- 10分钟教会你Apache Shiro
- iOS网络编程之JSON简单介绍
- Objective-C:Day5
- 平铺图片被截图时页面卡死2秒钟的问题
- final 实例域+final类+final方法(阻止继承)