我最近嘗試進入 OOP 以進入更高級的 python。我想做一個類中的函式串列。我從不使用開始self.functionName = functionName,這導致無法在串列中識別功能的錯誤。所以我假設你在__init__函式中寫的東西在類中作為全域函式作業,所以我添加self了前兩個函式,以便它們可以在另一個函式中使用,并且它作業正常。但是,當我添加self到最后一個函式時,我沒有得到相同的答案,這是為什么呢?
這是我寫的代碼:
>>> class number: #works fine, no self.ans
def __init__(self):
self.numOne = numOne
self.numTwo = numTwo
def numOne(self):
print("one")
def numTwo(self):
print("two")
def ans(self):
bruh = [numOne, numTwo]
for i in bruh:
i()
>>> a = number()
>>> a.ans()
one
two
>>> class number: #now when I write self.ans
def __init__(self):
self.numOne = numOne
self.numTwo = numTwo
self.ans = ans
def numOne(self):
print("one")
def numTwo(self):
print("two")
def ans(self):
bruh = [numOne, numTwo]
for i in bruh:
i()
>>> a = number()
>>> a.ans()
<generator object ans.<locals>.<genexpr> at 0x0000021476FDBF90> #this is the result
>>>
uj5u.com熱心網友回復:
您不需要將方法分配給建構式中的實體。這已經是課程運作方式的一部分。
這可以正常作業:
class Number:
def num_one(self):
print("one")
def num_two(self):
print("two")
def ans(self):
bruh = [self.num_one, self.num_two]
for i in bruh:
i()
n = Number()
n.ans()
結果:
one
two
當然,__init__如果你需要設定一些初始值,你仍然可以有一個,但是一個類不需要自定義建構式。只需將其宣告為class,它就會有一個建構式,您可以根據需要覆寫該建構式。
順便說一句,您最好用以大寫字母開頭的名稱來命名您的類。用駱駝大寫命名方法更像是一種品味,但我覺得下劃線更pythonic - 但是絕對可以使用大寫字母,以避免人們混淆物件和類。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/404782.html
標籤:
