美文网首页
廖雪峰Python学习笔记之面向对象高级编程

廖雪峰Python学习笔记之面向对象高级编程

作者: redLion | 来源:发表于2015-11-03 10:34 被阅读86次

先记录一下代码,后续补全学习体会。

1.使用slots

class Student(object): pass

s = Student() s.name='Michael' #动态给实例绑定一个属性 print s.name

def set_age(self,age): #定义一个函数作为实例方法 self.age=age

from types import MethodType s.set_age=MethodType(set_age,s,Student) #给实例绑定一个方法 s.set_age(25) #调用实例方法 s.age #测试结果

s2=Student() #创建新的实例 s2.set_age(25) #尝试调用方法

def set_score(self,score): self.score=score Student.set_score=MethodType(set_score,None,Student) s.set_score(100) s.score s2.set_score(99) s2.score

class Student(object): __slots__=('name','age') #用tuple定义允许绑定的属性名称 s=Student() #创建新的实例 s.name='Micheal' #绑定属性name s.age=25 # 绑定属性age s.score=99 #绑定属性score

class GraduateStudent(Student): pass g=GraduateStudent() g.score=9999

2.使用@property

code_snap_1:

class Student(object): def get_score(self): return self._score def set_score(self,value): if not isinstance(value,int): raise ValueError('score must be an integer!') if value<0 or value>100: raise ValueError('score must between 0 ~ 100!') self._score=value

s=Student() s.set_score(60) s.get_score() s.set_score(9999)

code_snap_2:

class Student(object): @property def score(self): return self._score @score.setter def score(self,value): if not isinstance(value,int): raise ValueError('score must be an integer!') if value<0 or value>100: raise ValueError('score must between 0 ~ 100!') self._score=value s=Student() s.score=60 s.score s.score=9999

code_snap_3:

class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self,value): self._birth=value @property def age(self): return 2014-self.birth s=Student() s.birth=1988 s.age

相关文章

  • 面向对象编程

    面向对象编程 参考廖雪峰的Python教程 面向对象编程-------Object Oriented Progra...

  • Python面向对象编程(二)

    本文我们继续介绍一些Python面向对象编程中的高级用法,依然参考廖雪峰老师的Python教程。 教程地址:htt...

  • 廖雪峰Python学习笔记之面向对象高级编程

    先记录一下代码,后续补全学习体会。 1.使用slots class Student(object): pass s...

  • 面向对象编程

    面向对象 --摘自廖雪峰官网面向对象编程---Object Oriented Programming,简称OOP,...

  • python面向对象学习笔记-01

    学习笔记 # 0,OOP-Python面向对象 - Python的面向对象 - 面向对象编程 - 基础 -...

  • 笨方法学python--ex39.py

    廖雪峰的面向对象编程:面向对象编程——Object Oriented Programming,简称OOP,是一种程...

  • 廖雪峰Python学习笔记之面向对象编程

    面向过程的编程思维是:按照处理流程,每一步需要做什么?用哪些函数可以解决?严格按照流程来把事情完成就ok了。这个在...

  • Day3:python基础(面向对象编程)

    今天主要学习的是python面向对象编程的基础,因为也很简单,不做记录。然后在这里真的要推荐廖雪峰的python3...

  • JavaScript学习笔记(五)

    主要源于廖雪峰老师的JavaScript教程 面向对象编程 1. 简介 JavaScript的面向对象编程和大多数...

  • 2015.4.15

    晴 学习内容 1.python 廖雪峰python教程面对对象高级编程部分,剩下定制类和元类还没看 2.计算机组成...

网友评论

      本文标题:廖雪峰Python学习笔记之面向对象高级编程

      本文链接:https://www.haomeiwen.com/subject/uceqhttx.html