Python 的 class attributes 和 instance attributes 的区别

上一篇博文提到,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环境了。
原作者的代码运行结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值