尧图建网站 尧图建网站 YAOTU WEB BUILD 免费咨询
ARTICLE DETAIL

资讯详情

深耕网站建设与建站编程的一线实战洞察。

【2014-04-09】Python面向对象编程基础笔记

【2014-04-09】Python面向对象编程基础笔记 RuFKvYfNPVQGDXf3PT4K[历史归档]本文原发布于 cstriker1407.info 个人博客内容为历史存档仅供参考。发布时间2014-04-09 标题Python面向对象编程基础笔记分类编程 / python jython 标签python jython·面向对象Python面向对象编程基础笔记创建一个类以及类实例方法使用\_\_init\_\_方法及\_\_del\_\_方法类变量与成员变量访问权限继承多重继承及super调用本笔记来源自【 http://sebug.net/paper/python/ch11.html#s01 】,有删改。创建一个类以及类实例方法类的方法与普通的函数只有一个特别的区别——它们必须有一个额外的第一个参数名称但是在调用这个方法的时候你不为这个参数赋值Python会提供这个值。这个特别的变量指对象本身按照惯例它的名称是self。classPerson:defsayHi(self):printHello, how are you?pPerson()p.sayHi()使用__init__方法及__del__方法classPerson:def__init__(self,name):self.namename defsayHi(self):printHello, my name is,self.name def__del__(self):pass;pPerson(Swaroop)p.sayHi()类变量与成员变量classPerson:#类变量 population0#构造函数 def__init__(self,name):#成员变量以及调用方式 self.namename print(Initializing %s)%self.name #类变量的调用方式 Person.population1#析构函数 def__del__(self):I am dying.print%s says bye.%self.name Person.population-1ifPerson.population0:printI am the last one.else:printThere are still %d people left.%Person.population defsayHi(self):Greeting by the person.Really,thats all it does.printHi, my name is %s.%self.name defhowMany(self):Prints the current population.ifPerson.population1:printI am the only person here.else:printWe have %d persons here.%Person.population swaroopPerson(Swaroop)swaroop.sayHi()swaroop.howMany()kalamPerson(Abdul Kalam)kalam.sayHi()kalam.howMany()swaroop.sayHi()swaroop.howMany()输出$ python objvar.py(Initializing Swaroop)Hi,my nameisSwaroop.I am the only person here.(Initializing Abdul Kalam)Hi,my nameisAbdul Kalam.We have2persons here.Hi,my nameisSwaroop.We have2persons here.Abdul Kalam says bye.There are still1people left.Swaroop says bye.I am the last one.访问权限Python中所有的类成员包括数据成员都是公共的 所有的方法都是 有效的 。只有一个例外如果你使用的数据成员名称以双下划线前缀比如__privatevarPython的名称管理体系会有效地把它作为私有变量。这样就有一个惯例如果某个变量只想在类或对象中使用就应该以单下划线前缀。而其他的名称都将作为公共的可以被其他类/对象使用。记住这只是一个惯例并不是Python所要求的与双下划线前缀不同。继承classSchoolMember:def__init__(self,name,age):self.namename self.ageage print(Initialized SchoolMember: %s)%self.name deftell(self):printName:%s Age:%s%(self.name,self.age),#继承的语法classTeacher(SchoolMember):def__init__(self,name,age,salary):#调用父类的构造函数 SchoolMember.__init__(self,name,age)self.salarysalary print(Initialized Teacher: %s)%self.name deftell(self):#重写父类的函数也可以看到如何调用父类的函数 SchoolMember.tell(self)printSalary: %d%self.salaryclassStudent(SchoolMember):def__init__(self,name,age,marks):SchoolMember.__init__(self,name,age)self.marksmarks print(Initialized Student: %s)%self.name deftell(self):SchoolMember.tell(self)printMarks: %d%self.marks tTeacher(Mrs. Shrividya,40,30000)sStudent(Swaroop,22,75)print # prints a blank line membersformember in members:member.tell()# worksforboth TeachersandStudents多重继承及super调用暂时用不到随用随学吧。【 http://www.cnblogs.com/lemoncolaz/p/3168574.html 】【 http://blog.csdn.net/caz28/article/details/8270709 】【 http://www.zhihu.com/question/20040039 】
返回列表