专栏名称: Python学习交流
每天更新,更新python相关的知识。希望诸君有所收获!
目录
相关文章推荐
Python开发者  ·  “李飞飞团队50 美元炼出 ... ·  昨天  
Python开发者  ·  国产 DeepSeek V3 ... ·  2 天前  
Python爱好者社区  ·  史上最强!PINN杀疯了 ·  昨天  
Python爱好者社区  ·  DeepSeek创始人梁文锋个人履历 ·  3 天前  
Python爱好者社区  ·  离谱!下载DeepSeek最高判刑20年? ·  2 天前  
51好读  ›  专栏  ›  Python学习交流

怎么学Python?面向对象是必须度过的坎!5万字长带你入门!

Python学习交流  · 公众号  · Python  · 2018-02-03 15:11

正文

继承 :即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。

另外,我们会发现在 重用 父类的代码的时候,我们无需在不同的类中重复它。而如果我们使用独立的类的话,我们就不得不这么做了。

使用继承

#!/usr/bin/python# Filename: inherit.pyclass SchoolMember:'''Represents any school member.'''def __init__(self, name, age):self.name = nameself.age = ageprint '(Initialized SchoolMember: %s)'% self.namedef tell(self):'''Tell my details.'''print 'Name:"%s" Age:"%s"' % (self.name, self.age),class Teacher(SchoolMember):'''Represents a teacher.'''def __init__(self, name, age, salary):SchoolMember.__init__(self, name, age)self.salary = salaryprint '(Initialized Teacher: %s)'% self.namedef tell(self):SchoolMember.tell(self)print 'Salary: "%d"' % self.salaryclass Student(SchoolMember):'''Represents a student.'''def __init__(self, name, age, marks):SchoolMember.__init__(self, name, age)self.marks = marksprint '(Initialized Student: %s)'% self.namedef tell(self):SchoolMember.tell(self)print 'Marks: "%d"' % self.markst = Teacher('Mrs. Shrividya', 40,30000)s = Student('Swaroop', 22,75)print # prints a blank linemembers = [t, s]for member in members:member.tell() # works for both Teachers and Students输出$ python inherit.py(Initialized SchoolMember: Mrs. Shrividya)(Initialized Teacher: Mrs. Shrividya)(Initialized SchoolMember: Swaroop)(Initialized Student: Swaroop)Name:"Mrs. Shrividya" Age:"40" Salary: "30000"Name:"Swaroop" Age:"22" Marks: "75"

#coding=utf-8#!/usr/bin/pythonclass Parent: # 定义父类parentAttr = 100def __init__(self):print "调用父类构造函数"def parentMethod(self):print '调用父类方法'def setAttr(self, attr):Parent.parentAttr = attrdef getAttr(self):print "父类属性 :", Parent.parentAttrclass Child(Parent): # 定义子类def __init__(self):print "调用子类构造方法"def childMethod(self):print '调用子类方法 child method'c = Child() # 实例化子类c.childMethod() # 调用子类的方法c.parentMethod() # 调用父类方法c.setAttr(200) # 再次调用父类的方法c.getAttr() # 再次调用父类的方法

方法重写

如果你的父类方法的功能不能满足你的需求,你可以在子类重写你父类的方法:

实例:

#coding=utf-8#!/usr/bin/pythonclass Parent: # 定义父类def myMethod(self):print '调用父类方法'class Child(Parent): # 定义子类def myMethod(self):print '调用子类方法'c = Child() # 子类实例c.myMethod() # 子类调用重写方法

执行以上代码输出结果如下:

调用子类方法基础重载方法

Python同样支持运算符重载,实例如下:

#!/usr/bin/pythonclass Vector:def __init__(self, a, b):self.a = aself.b = bdef __str__(self):return 'Vector (%d, %d)' % (self.a, self.b)def __add__(self,other):return Vector(self.a + other.a, self.b + other.b)v1 = Vector(2,10)v2 = Vector(5,-2)print v1 + v2以上代码执行结果如下所示:Vector(7,8)

#coding=utf-8#!/usr/bin/pythonclass JustCounter:__secretCount = 0 # 私有变量publicCount = 0 # 公开变量def count(self):self.__secretCount += 1self.publicCount += 1print self.__secretCountcounter = JustCounter()counter.count()counter.count()print counter.publicCountprint counter.__secretCount # 报错,实例不能访问私有变量

抽象是隐藏多余细节的艺术。在面向对象的概念中,抽象的直接表现形式通常为类。虽然Python是解释性语言,但是它是面向对象的,从设计之初就已经是一门面向对象的语言。Python基本上提供了面向对象编程语言的所有元素,如果你已经至少掌握了一门面向对象语言,那么利用Python进行面向对象程序设计将会相当容易。下面就来了解一下如何在Python中进行对象编程。

内置方法 说明
__init__(self,...) 初始化对象,在创建新对象时调用
__del__(self) 释放对象,在对象被删除之前调用
__new__(cls,*args,**kwd) 实例的生成操作
__str__(self) 在使用print语句时被调用
__getitem__(self,key) 获取序列的索引key对应的值,等价于seq[key]
__len__(self) 在调用内联函数len()时被调用
__cmp__(stc,dst) 比较两个对象src和dst
__getattr__(s,name) 获取属性的值
__setattr__(s,name,value) 设置属性的值
__delattr__(s,name) 删除name属性
__getattribute__() __getattribute__()功能与__getattr__()类似
__gt__(self,other) 判断self对象是否大于other对象
__lt__(slef,other) 判断self对象是否小于other对象
__ge__(slef,other) 判断self对象是否大于或者等于other对象
__le__(slef,other) 判断self对象是否小于或者等于other对象
__eq__(slef,other) 判断self对象是否等于other对象
__call__(self,*args) 把实例对象作为函数调用







请到「今天看啥」查看全文