python可以继承父类方法吗
python继承,调用父类属性方法
在python里面,继承一个类只需要这样写:
classAnimal:
defheshui(self):
print('动物正在喝水')
classCat(Animal):
pass
这样Cat就有了Animal的所有属性和方法,调用的时候直接调用就可以了:
#接上面代码
cat=Cat()
cat.heshui()
>>>动物正在喝水
这个时候,如果子类想重写父类的方法,可以直接重写:
classAnimal:
defheshui(self):
print('动物正在喝水')
classCat(Animal):
defheshui(self):
print('猫正在喝水')
cat=Cat()
cat.heshui()
>>>猫正在喝水
如果想调用父类的heshui这个方法,可以用super():
classAnimal:
defheshui(self):
print('动物正在喝水')
classCat(Animal):
defheshui(self):
super().heshui()
cat=Cat()
cat.heshui()
>>>动物正在喝水
强制调用父类私有属性方法
如果父类的方法是私有方法,如def__heshui(self)这样的话再去调用就提示没有这个方法,其实编译器是把这个方法的名字改成了_Animal__heshui(),如果强制调用,可以这样:
classAnimal:
def__heshui(self):
print('动物正在喝水')classCat(Animal):
defheshui(self):
super()._Animal__heshui()
cat=Cat()
cat.heshui()>>>动物正在喝水
最后,如果自己也定义了__init__方法,那么父类的属性是不能直接调用的:
classAnimal:
def__init__(self):
self.a='aaa'
classCat(Animal):
def__init__(self):
pass
cat=Cat()
print(cat.a)
>>>AttributeError:'Cat'objecthasnoattribute'a'
那么可以在子类的__init__中调用一下父类的__init__方法,这样就可以调用了:
classAnimal:
def__init__(self):
self.a='aaa'classCat(Animal):
def__init__(self):
super().__init__()#也可以用Animal.__init__(self)这里面的self一定要加上
cat=Cat()
print(cat.a)>>>aaa
以上内容为大家介绍了python培训之可以继承父类方法吗,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。

猜你喜欢LIKE
相关推荐HOT
更多>>
python中如何dataframe转换为ndarray?
python中如何dataframe转换为ndarray?小编介绍过python中ndarray与series如何相互转换的方法,其实Series转换为ndarray是一个一维数组,作为pan...详情>>
2023-11-14 05:21:25
python中os.remove()的使用注意
python中os.remove()的使用注意计算机一般来说是需要定期的清理,系统的内存不能延伸,同时有一些不需要的文件也可以得以清除掉。有些人会使用o...详情>>
2023-11-14 04:47:11
python元组的优势有哪些
python元组的优势有哪些本文教程操作环境:windows7系统、Python3.9.1,DELLG3电脑。1、因为元素不可变性,它可以作为哈希类型的key值。这样使...详情>>
2023-11-14 03:55:04
python如何获取当前文件的部分信息?
python中如何获取当前文件的部分信息?一、文件对象常用的属性1、file.name:文件的名称2、file.mode:打开文件时,采用的文件打开模式3、file.e...详情>>
2023-11-14 03:24:14热门推荐
python中如何应用视图函数?
沸python根据键值(value)返回键(key)
热python中pickle模块是什么?
热python解析json文件方法
新python中如何dataframe转换为ndarray?
python中os.remove()的使用注意
Python中if嵌套是什么?
python元组的优势有哪些
python如何获取当前文件的部分信息?
Python使用平面文件进行存储
python中remove()方法如何使用删除后的值?
python如何使用RE正则表达检验字符串
pythonSelenium操作Cookie的方法
python类方法的注意点
技术干货






