《用Python玩转数据》Week 5, Part 1

本文探讨Python中Class属性与实例属性的区别,通过示例展示如何使用Class.attribute,并指出self.attribute作为类实例的私有属性的特性。同时推荐了wxPython的学习资源,包括博客和教程链接。

1、看例子:

class Roster(object):
    'This is a class roster program.'
    teacher_name = ''
    students = []
    def __init__(self):
        Roster.teacher_name = 'Lily'
        print '%s is this class teacher.' % Roster.teacher_name
    def add(self, student_name):
        Roster.students.append(student_name)
        print '%s has join the class.' % student_name
    def remove(self, student_name):
        if student_name in Roster.students:
            Roster.students.remove(student_name)
            print '%s has been removed.'
        else:
            print '%s was not in this class.' % student_name
    def print_all(self):
        print 'Teacher:', Roster.teacher_name
        print 'Students:', Roster.students

在《An Introduction to Interactive Programming in Python》的课程中我学到了在Class里面变量都需要用self.attribute来表示。但是,现在又学到一种新方法,在Class里面可以直接用Class.attribute来调用自己的变量。上面的例子,所有应该用self.teacherself.students 的地方,都用了Roster.teacher, Roster.students 。那么有什么不同呢?执行一下看看:

In [20]: roster = Roster()
Lily is this class teacher.

In [21]: roster.add('Xiaoming')
Xiaoming has join the class.

In [22]: roster.print_all()
Teacher: Lily
Students: ['Xiaoming']

新增一个花名册,直接print_all:

In [23]: roster2 = Roster()
Lily is this class teacher.

In [24]: roster2.print_all()
Teacher: Lily
Students: ['Xiaoming']

In [25]: 

可以看到,roster2没有添加任何学生,但是在花名册里面却已经有Xiaoming了。self.teacher是类实例的私有属性,而roster.teacher是类属性,是每个实例共用的,类似于全局变量。在编程时应该尽量使用self.attribute

2、wxPython学习资源
再吐槽一次:用PPT讲课就是一场灾难。国内的老师热衷于讲解名词,概念,而老外根本就不用PPT,就是让你跟着他动手,在编程的过程中学习编程。
http://www.cnblogs.com/coderzh/archive/2008/11/23/1339310.html
Python天天美味系列很不错,不过这里的博客将不再更新,最新博客请移步至:
http://blog.coderzh.com/
还有IBM的教程:
http://www.ibm.com/developerworks/cn/linux/sdk/python/wxpy/index.html
发现一个学习Python的网站:Pythoner
http://www.pythoner.cn/course/topic/wxPython-gui/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值