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环境了。
原作者的代码运行结果

0 0
原创粉丝点击