面对对象高级编程

给实例绑定方法

class Student(object):
      def get_score(self):
          print(self.score)

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

from types import MethodType
s = Student()
s.set_score = MethodType(set_score,s) # 给实例s绑定一个set_score方法
s.set_score(40)
s.get_score()

需要注意的是,给一个实例绑定的方法,另一个实例不能使用。

给类绑定方法

Student.set_score = MethodType(set_score, Student)

通过上面的定义,所有实例均可使用该方法。

class Student(object):
      def __init__(self,score):
            self.score = score
      def get_score(self):
          print(self.score)

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

from types import MethodType
s = Student(20)
Student.set_score = MethodType(set_score, Student)
s.set_score(40)
s.get_score()

如上述程序,当给有关键字_init_的类绑定方法是不起作用的,但是给实例绑定方法能起作用。
进一步,当绑定方法要修改private属性时,对也不起作用。

class Student(object):
      def __init__(self,score):
            self.__score = score
      def get_score(self):
          print(self.__score)

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


from types import MethodType
s = Student(20)
s.set_score = MethodType(set_score, s)
s.set_score(40)
s.get_score()

猜想:绑定方法修改时可能修改的是类属性,由实例属性优先级高于类属性的特点,当同名时从而表面上显示不起作用?

使用slots

当我们需要限制类所添加的属性时,可以使用_slots_关键字

class Student(object):
      __slots__ = ('name','age')

s.name = 'peter'
s.age = 10
s.score = 10

需要注意的是,_slots_关键字只对当前类的实例有用!!对继承的子类不起作用。

使用@property

使用@property可以使方法编程属性来调用。

class Stu(object):
    @property
    def score(self):
        return self.__score

    @score.setter
    def score(self,score):
        self.__score = score

如上例子,用@property修饰的方法相当于score的getter方法,相应的setter方法用@score.setter修饰。
而且需要注意的是如果

class Stu(object):
    @property
    def score(self):
        return self.score

    @score.setter
    def score(self,value):
        self.score = value


s = Stu()
s.score = 90
print(s.score)

会出现RuntimeError

多重继承

与Java的单继承不同,Python支持多重继承。
需要注意的时,子类调用的方法是安装夫类的顺序查找的,即当子类调用的方法在一个夫类中第一次查找到,调用该夫类的方法。

class Man(object):
    def hello(self):
        print('I\'m a man')




class Kid(object):
    def hello(self):
        print('I\'m a kid')


class Stu1(Kid,Man):
    pass

class Stu2(Man,Kid):
   pass


s = Stu1()

s.hello()

s2 = Stu2()

s2.hello()

版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2015-08-30 15:15  mlhy  阅读(235)  评论(0编辑  收藏  举报