您的位置:首页 > 编程语言 > Python开发

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. 用文章中的一段代码来说明就清楚了:

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