标签(空格分隔): python
python中类的定义,括号内是继承的类,所有的类都默认继承自object类
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
1.数据的封装
意思是直接在类里面定义函数,去调用、显示其它函数的结果。而不是在类外访问。
外部访问,在类外定义函数访问类里面的数据
>>> def print_score(std):
... print '%s: %s' % (std.name, std.score)
...
>>> print_score(bart)
Bart Simpson: 59
封装后的访问,直接在类内定义访问的函数
>>> bart.print_score()
Bart Simpson: 59
2.访问限制
变量前边有两个下划线,是私有变量。只有类内部可以访问,外部不能访问,一般这样的私有变量,都有配套的get,set函数。如果非要在类外访问,可以用get函数访问,用set函数修改
比如,在类外通过对象调用,会失败
>>> bart.__name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Student' object has no attribute '__name'
class Student(object):
...
def set_score(self, score):
self.__score = score
一个下划线,意思是我虽然可以访问,但不要随便访问。
前面两个下划线,后面两个下划线,是特殊变量,特殊变量在可以访问,
4.继承和多态
继承
当子类和父类都存在相同的run()方法时,我们说,子类的run()覆盖了父类的run(),在代码运行的时候,总是会调用子类的run()。这样,我们就获得了继承的另一个好处:多态。
父类
class Animal(object):
def run(self):
print 'Animal is running...'
子类
class Dog(Animal):
def run(self):
print 'Dog is running...'
def eat(self):
print 'Eating meat...'
继承
class Dog(Animal):
pass
class Cat(Animal):
pass
再次运行
dog = Dog()
dog.run()
cat = Cat()
cat.run()
结果
Dog is running...
Cat is running...
继承了就有多态了。
继承了就具有父类的方法,然后子类就能够覆写父类方法。
这样的好处就是,一个方法名在不同的子类里具有不同的作用,这就是多态。
定义一个函数,它的传入参数类型为animal类对象,也可以为annimal的派生类对象,dog,cat,它会自动调用子类的run函数
def run_twice(animal):
animal.run()
animal.run()