- 根据参考文献3: Python类之继承
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person): # Child 继承 Person
pass
May = Child("May","female")
Peter = Person("Peter","male")
print(May.name,May.sex,Peter.name,Peter.sex) # 子类继承父类方法及属性
May.print_title()
Peter.print_title()
- 根据参考文献3: Python类之多态
class Person(object):
def __init__(self,name,sex):
self.name = name
self.sex = sex
def print_title(self):
if self.sex == "male":
print("man")
elif self.sex == "female":
print("woman")
class Child(Person): # Child 继承 Person
def print_title(self):
if self.sex == "male":
print("boy")
elif self.sex == "female":
print("girl")
May = Child("May","female")
Peter = Person("Peter","male")
print(May.name,May.sex,Peter.name,Peter.sex)
May.print_title()
Peter.print_title()
- 根据参考文献1(类和实例): Python类之init方法
class Ball:
def __init__(self,name):
self.name=name
def kick(self):
print("我叫%s,谁踢我!" % self.name)
a=Ball("qiang")
a.kick()
- 根据参考文献1(访问限制): Python类之公有和私有
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def print_score(self):
print('%s: %s' % (self.__name, self.__score))
a=Student("yeqiang",100)
a.print_score()
- 根据参考文献4(038类和对象:继承)、参考文献5: Python之子类调用父类构造方法
1.方法一:调用未绑定的超类构造方法;
2.方法二:使用super函数。
- 根据参考文献3: Python类之多继承
可能会产生代码混乱,尽量不要用
- 根据参考文献4(039类和对象:拾遗): Python类之组合
class Turtle(object):
def __init__(self,x):
self.num = x
class Fish(object):
def __init__(self,y):
self.num = y
class Pool(object):
def __init__(self,x,y):
self.turtle = Turtle(x) //所谓的组合就是将类实例化放到一个新的类里面
self.fish = Fish(y)
def print_num(self):
print("水池里有 %d 只乌龟, %d " %(self.turtle.num,self.fish.num))
pool = Pool(1,2)
pool.print_num()
参考文献:
1. 廖雪峰Python教程
2. Python 面向对象
3. Python 类的继承和多态
4. 小甲鱼的Python视频教程-零基础入门学习Python
5. python中子类调用父类构造方法