Python 面向对象编程

2017-12-08  本文已影响0人  E_H_I_P

面向对象编程——Object Oriented Programming(OOP)

OOP 把对象作为程序的基本单元,一个对象包含了数据和操作数据的函数。
抽象类实体对象,类不能对数据成员进行赋值。【Class 是一种抽象概念,而实例( Instance)则是一个个具体的 Student】

知识点:数据封装,访问控制,继承,多态。

数据封装:数据和逻辑被“封装”起来了,调用很容易,而不用知道内部实现的细节

访问控制:可以对参数做检查,避免传入无效的参数。

class Student(object):
    ...
    def set_score(self, score):
        if 0 <= score <= 100:
            self.__score = score
        else:
            raise ValueError('bad score')

继承:

# -*- coding: utf-8 -*-
# 继承就是可以起到功能扩展的功能,父类可以创建通用方法,子类可以调用,也可以重新写自己的方法
# 当子类和父类存在相同的方法时,子类的方法会覆盖父类的方法。
class Animal(object):
    def run(self):
        print("Animal is running on the road!...")
        
class Dog(Animal):
    def run(self):
        print("Dog is running!")
class Cat(Animal):
    pass

dog = Dog()
dog.run()
cat = Cat()
cat.run()
print(isinstance(a,list))
print(isinstance(b,Animal))
print(isinstance(c,Dog))
print(isinstance(c,Animal))#子类一定属于其父类,反之则不行

多态:调用方只管调用,不管细节

  • 定义一个class的时候实际上就定义了一种数据类型。
上一篇 下一篇

猜你喜欢

热点阅读