面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,每个对象都拥有相同的方法,但各自的数据可能不同。
仍以Student类为例,在Python中,定义类是通过 class Student(object): pass
定义好了 >>> bart = Student() >>> bart <__main__.Student object at 0x10a67a590> >>> Student <class '__main__.Student'>
可以看到,变量
可以自由地给一个实例变量绑定属性,比如,给实例 >>> bart.name = 'Bart Simpson' >>> bart.name 'Bart Simpson'
由于类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的 class Student(object): def __init__(self, name, score): self.name = name self.score = score
注意到
有了 >>> bart = Student('Bart Simpson', 59) >>> bart.name 'Bart Simpson' >>> bart.score 59
和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量 数据封装
面向对象编程的一个重要特点就是数据封装。在上面的 >>> def print_score(std): ... print '%s: %s' % (std.name, std.score) ... >>> print_score(bart) Bart Simpson: 59
但是,既然 class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print '%s: %s' % (self.name, self.score)
要定义一个方法,除了第一个参数是 >>> bart.print_score() Bart Simpson: 59
这样一来,我们从外部看
封装的另一个好处是可以给 class Student(object): ... def get_grade(self): if self.score >= 90: return 'A' elif self.score >= 60: return 'B' else: return 'C'
同样的, >>> bart.get_grade() 'C'
小结类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响; 方法就是与实例绑定的函数,和普通函数不同,方法可以直接访问实例的数据; 通过在实例上调用方法,我们就直接操作了对象内部的数据,但无需知道方法内部的实现细节。 和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同: >>> bart = Student('Bart Simpson', 59) >>> lisa = Student('Lisa Simpson', 87) >>> bart.age = 8 >>> bart.age 8 >>> lisa.age Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'age' 转载请保留固定链接: https://linuxeye.com/program/2373.html |