【发布时间】:2022-01-06 22:39:56
【问题描述】:
我最近尝试进入 OOP 以迈向更高级的 python。我想做一个类中的函数列表。我从 not 开始使用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
>>>
【问题讨论】:
-
你不需要像
self.numOne = numOne这样的语句——通过在类的主体中定义numOne,它自动成为类的一部分,每个对象都可以调用self.numOne() -
@Grismar 这定义了一个名为
numOne的 class 属性,其行为与 instance 属性不同。如果它是可变值,则差异非常重要。 -
列表必须是
bruh = [self.numOne, self.numTwo]。这里不需要init函数。 -
应该有很多
NameErrors 被提出,因为你没有定义全局变量。第二个a.ans()的结果表明您定义了许多尚未显示的变量,并且与您尝试构建的示例没有真正的关系。