【python38--面向对象继承】

一、继承

1、语法:class DerivedClassName(BaseClassName):子类继承父类

>>> class Parent:
    def hello(self):
        print('正在调用父类的方法。。。')

        
>>> class Child(Parent):
    pass

>>> p = Parent()
>>> p.hello()
正在调用父类的方法。。。
>>> c = Child()
>>> c.hello()
正在调用父类的方法。。。
>>> 
#子类Child继承了父类Parent,所以子类可以调用父类的方法c.hello()

2、如果子类中定义的方法和属性和父类的属性和方法名字一样,则会自动覆盖父类对应的方法和属性

import random as r

class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)

def move(self):
self.x -=1
print('我的位置',self.x,self.y)

class Goldfish(Fish):
pass

class Carp(Fish):
pass

class Salmon(Fish):
pass

class Shark(Fish):
def __init__(self):
self.hungry = True

def eat(self):
if self.hungry:
print('吃货的梦想就是天天吃肉!')
self.hungry = False
else:
print('吃撑了!')

>>> fish = Fish()
>>> fish.move()
我的位置 4 7
>>> goldfish = Goldfish()
>>> goldfish.move()
我的位置 6 5
>>> carp = Carp()
>>> carp.move()
我的位置 7 6
>>> salmon = Salmon()
>>> salmon.move()
我的位置 -1 10
>>> shark = Shark()
>>> shark.move()
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
shark.move()
File "/Users/yixia/Desktop/fish.py", line 9, in move
self.x -=1
AttributeError: 'Shark' object has no attribute 'x'

---报错的原因:AttributeError: 'Shark' object has no attribute 'x'  :Shark没有x的属性,shark继承了Fish,为什么会没有x的属性呢

原因:Shark重写了__init__的方法,就会覆盖父类Fish的__init__()方法中的x属性,即:子类定义类一个和父类相同名称的方法,则会覆盖父类的方法和属性

改正的代码:

两种方法:1,调用未绑定的父类方法  2、使用super()函数

实现的代码如下:

第一种:

import random as r

class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)

def move(self):
self.x -=1
print('我的位置',self.x,self.y)

class Goldfish(Fish):
pass

class Carp(Fish):
pass

class Salmon(Fish):
pass

class Shark(Fish):
def __init__(self):
Fish.__init__(self) #父类名称调用__init__()函数
self.hungry = True

def eat(self):
if self.hungry:
print('吃货的梦想就是天天吃肉!')
self.hungry = False
else:
print('吃撑了!')

>>> shark = Shark()
>>> shark.move()
我的位置 1 8
>>>

第二种:

import random as r

class Fish:
def __init__(self):
self.x = r.randint(0,10)
self.y = r.randint(0,10)

def move(self):
self.x -=1
print('我的位置',self.x,self.y)

class Goldfish(Fish):
pass

class Carp(Fish):
pass

class Salmon(Fish):
pass

class Shark(Fish):
def __init__(self):
super().__init__() #采用super()函数
self.hungry = True

def eat(self):
if self.hungry:
print('吃货的梦想就是天天吃肉!')
self.hungry = False
else:
print('吃撑了!')

>>> shark = Shark()
>>> shark.move()
我的位置 -1 6

猜你喜欢

转载自www.cnblogs.com/frankruby/p/9551473.html