簡體   English   中英

從子 class 調用父方法的正確方法

[英]The proper way to call a parent method from a child class

我正在嘗試使用子 class 的父方法。 下面給出了一個簡單的例子。

class one:
    def multiply(self, x, y):
        self.x = 500
        return self.x*y
        
class two(one):
    def multiplier(self, x, y):
        self.x = x
        
        ver1 = one.multiply(one, self.x, y)  # here, if I don't pass one as an argument, I get a TypeError
        print('The answer of ver1:', ver1)
        print('What is self.x btw?', self.x)
        
        ver2 = super().multiply(self.x, y)
        print('The answer of ver2:', ver2)
        print('What is self.x now?', self.x)

t = two()
t.multiplier(3,4)

這打印:

The answer of ver1: 2000
What is self.x btw? 3
The answer of ver2: 2000
What is self.x now? 500

我在這里看了很多答案似乎暗示ver2是調用父方法的正確方法,但我不希望self.x在子 class 中發生變化,所以我想要的答案是ver1 但是,在ver1中,當已經指定multiplyone的方法時,將one作為參數傳遞似乎是多余的(如果我不將one作為參數傳遞,我會得到

TypeError: multiply() missing 1 required positional argument: 'y'

那么從父 class 調用方法而不更改子 class 中的變量的正確方法是什么?

使用self ,而不是one

class two(one):
    def multiplier(self, x, y):
        self.x = x
        
        ver1 = self.multiply(x, y)
        print('The answer of ver1:', ver1)
        print('What is self.x btw?', self.x)

如果您覆蓋相同的方法但想要訪問父級,則 Super 很有用:

class two(one):
    def multiply(self, x, y):
        self.x = x
        
        ver2 = super().multiply(x, y)
        print('The answer of ver2:', ver2)
        print('What is self.x now?', self.x)

當已經指定乘法是一個方法時,將一個作為參數傳遞似乎是多余的(如果我不將一個作為參數傳遞,我會得到 TypeError: multiply() missing 1 required positional argument: 'y')

這是因為當您使用self時,該方法綁定到實例,並且實例作為第一個參數自動傳遞。 使用one.multiply時,方法不綁定,需要手動傳遞。 但這不是您直覺的 go 的正確方法。

我不希望 self.x 在子 class 中發生變化

由於 inheritance,有兩個類和一個實例,這是兩個類的實例。 x 是一個實例屬性,因此它屬於實例,而不屬於兩個類中的任何一個。 它不能在父母而不是孩子 class 或相反的情況下改變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM