我在一個類中有許多方法,我需要呼叫一個特定的方法。我嘗試了這樣的事情,但得到了一個 AttributeError
class MyClass:
def first(a, b):
return a b
def second(a, b):
return a * b
a = 2
b = 3
first_func = MyClass.first
second_func = MyClass.second
my_obj = MyClass()
我希望下面的一些東西可以作業,但我得到了這個例外:
my_obj.first_func(a, b) my_obj.second_func(a, b) == 11
那么有沒有辦法做到這一點?
uj5u.com熱心網友回復:
我們應該在這里討論幾件事。我將嘗試解釋不同的場景,以便為您提供一個概覽,看看發生了什么。
首先讓我們看看你的最后一行:
my_obj.first_func(a, b) my_obj.second_func(a, b)
您正在嘗試first_func從實體中獲取屬性my_obj。它(或它的類)有嗎?No.
first_func是全域模塊中的變數。my_obj對此一無所知。
因此,因此引發了您的例外...
現在考慮你的方法:
first和second方法是你類中的常規方法。當你說MyClass.first,你得到的是一個函式物件而不是一個方法。這個函式接受兩個引數a和b。
但是如果你說my_obj.first_func你得到一個方法物件,它有一個系結的實體物件。Python 使用對呼叫此方法的實體的參考為您填充第一個引數。現在您的方法物件只接受一個引數b。(這就是描述符的作業方式)
話雖如此,您在這里有一些選擇:
1 - 僅從類而不是實體中呼叫它們:
否則你會得到例外,因為 Python 已經用實體物件填充了第一個引數。
class MyClass:
def first(a, b):
return a b
def second(a, b):
return a * b
first_func = MyClass.first
second_func = MyClass.second
print(first_func(2, 3) first_func(2, 3))
2- 裝飾它們staticmethod:
現在您可以從實體或類中呼叫,Python 不會為您填充第一個引數。
class MyClass:
@staticmethod
def first(a, b):
return a b
@staticmethod
def second(a, b):
return a * b
first_func = MyClass.first
second_func = MyClass.second
print(first_func(2, 3) first_func(2, 3))
class MyClass:
@staticmethod
def first(a, b):
return a b
@staticmethod
def second(a, b):
return a * b
my_obj = MyClass()
first_func = my_obj.first
second_func = my_obj.second
print(first_func(2, 3) first_func(2, 3))
3-添加一個self引數(它的名稱不是規則,而是強烈推薦的約定):
這一次,如果你從實體呼叫它們,你不需要將實體傳遞給第一個引數,但是如果你從類呼叫它們,你需要將它作為第一個引數傳遞。
class MyClass:
def first(self, a, b):
return a b
def second(self, a, b):
return a * b
my_obj = MyClass()
first_func = my_obj.first
second_func = my_obj.second
print(first_func(2, 3) first_func(2, 3))
class MyClass:
def first(self, a, b):
return a b
def second(self, a, b):
return a * b
my_obj = MyClass()
first_func = MyClass.first
second_func = MyClass.second
print(first_func(my_obj, 2, 3) first_func(my_obj, 2, 3))
uj5u.com熱心網友回復:
類中的函式定義應包含“self”作為引數
class MyClass:
def first(self,a, b):
return a b
def second(self,a, b):
return a * b
a = 2
b = 3
first_func = MyClass.first
second_func = MyClass.second
my_obj = MyClass()
first_func(my_obj,a, b) second_func(my_obj,a, b) == 11
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465543.html
上一篇:有沒有辦法在處理中附加一組物件?
