python学习——面向对象高级编程

给类/实例动态绑定方法

from types import MethodType
class Student(object):
    pass

def set_age(self, age):
    self.age = age

def set_score(self, score):
    self.score = score

# 给实例绑定一个方法
a = Student()
a.set_age = MethodType(set_age, a)
a.set_age(20)
print(a.age)

# 给类绑定一个方法
# Student.set_score = MethodType(set_score, Student)
Student.set_score = set_score   #方法二
b = Student()
b.set_score(90)
print(b.score)

 一般情况下,可以将方法先写在父类里更加方便

 

访问限制

要让内部属性不被外部访问,可将属性名称前面加__ ,如__gender  这样就变成一个私有变量,只可以内部访问

class Student(object):
    def __init__(self, name, gender):
        self.__name = name
        self.__gender = gender

    def get_gender(self):
        return self.__gender

    def set_gender(self, gender):
        self.__gender = gender

bart = Student('bart','male')
print(bart.get_gender())

bart.set_gender('female')
print(bart.get_gender())

 

继承与多态

python中继承与多态,我的个人理解是:
继承是子类继承父类的全部属性和方法,多态是子类对父类的方法表现多样化,如覆盖父类里的方法和添加新的方法

python的鸭子特性:不一定要传入父类的类型,只要保证传入的对象有要调用的方法就可以
对于静态语言(例如Java)来说,如果需要传入Animal类型,则传入的对象必须是Animal类型或者它的子类,否则,将无法调用run()方法。
对于Python这样的动态语言来说,则不一定需要传入Animal类型。我们只需要保证传入的对象有一个run()方法就可以了
#coding:utf-8

class Animal(object):
    def run(self):
        print('Animal is running')

class Dog(Animal):
    def run(self):
        print('Dog is running')

class Cat(Animal):
    def run(self):
        print('Cat is running')  #子类run方法会覆盖父类的run方法

a = Dog()
b = Cat()
isinstance(a, Animal)
isinstance(b, Animal)

def run_twice(Animal):
    Animal.run()

run_twice(a)
run_twice(b)

实例属性和类属性

实例属性属于各个实例所有,互不干扰;
类属性属于类所有,所有实例共享一个属性;
不要对实例属性和类属性使用相同的名字,否则将产生难以发现的错误。

练习:为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加
class Student(object):
    count = 0

    def __init__(self, name):
        self.name = name
        Student.count += 1

a1 = Student('Bart')
a2 = Student('Elle')
print(Student.count)

 

posted @ 2019-05-18 22:04  stacy_hu  阅读(150)  评论(0编辑  收藏  举报