继承(python)

一、基础知识

(一)定义:子类能继承父类所有的公有属性和公有方法(先使用子类的方法、属性)

(二)格式:

class 子类名(父类名):

#父类
class Phone():
    def phone_call(self,number):
        print(f"正在给{number}打电话!")
#子类
class Iphone(Phone):
    def carmera(self):
        print("正在拍照!")

phone=Iphone()
phone.carmera()
phone.phone_call(1345678345)
#结果
正在拍照!
正在给1345678345打电话!

二、在子类中间接调用父类私有属性和私有方法

#父类
class Phone():
    #父类私有方法
    def __number(self,number):
        self.list1= [number]
        print(self.list1)

    def phone_call(self):
        print("正在给打电话!")
        #子类无法直接修改父类私有方法,但可以间接调用
        self.__number(100867)
#子类
class Iphone(Phone):
    def carmera(self):
        print("正在拍照!")
    def show_number(self):
        self.phone_call()#此时调用了父类的私有方法

phone=Iphone()
phone.show_number()
#结果
正在给打电话!
[100867]

你可能感兴趣的:(python,开发语言)