多语言展示
当前在线:1810今日阅读:27今日分享:41

如何在PYTHON里对class进行方法的覆盖和重写

如何在PYTHON里对class进行方法的覆盖和重写
工具/原料

python3.7

方法/步骤
1

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    pass longWallet = L_Wallet()longWallet.store() #我们知道子类可以继承父类的方法,但是如果子类的方法想改动呢?

2

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    def store(self):        print('store the money') longWallet = L_Wallet()longWallet.store() #我们可以直接改动子类的方法,方法名字一样的情况下,里面的内容是可以修改的,返回的是覆盖的结果。但是如果我们要用回父类的方法呢?

3

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    def store(self):        print('store the money')         super().store() longWallet = L_Wallet()longWallet.store() #这个时候我们可以用super()调用父类的方法。

4

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    def store(self):        print('store the money')         super().store()        print('take out the cash') longWallet = L_Wallet()longWallet.store() #即使后面加多少内容,都是不影响的。

5

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    def store(self):        print('store the money')         Wallet.store() longWallet = L_Wallet()longWallet.store() #那如果直接调用父类名称来调用可以吗?是可以的,但是这里有一个错误。

6

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    def store(self):        print('store the money')         Wallet.store(self) longWallet = L_Wallet()longWallet.store() #务必记得加上self。

7

class Wallet:    def store(self):        print('store credit cards')        class L_Wallet(Wallet):    def store(self):        print('store the money')         L_Wallet.store(self)        longWallet = L_Wallet()longWallet.store() #如果自己调用自己会形成递归,这样会出现死循环。

注意事项

代码应该避免死循环

推荐信息