__init__ 中的 self.function 对函数有什么作用?
What does self.function in __init__ do to a function?
我最近尝试进入 OOP 以迈向更高级的 python。我想在 class 中做一个函数列表。我从 而不是 使用 self.functionName = functionName
开始,这导致无法在列表中识别函数的错误。所以我假设你在 __init__
函数中编写的内容在 class 中作为全局函数工作,所以我将 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
>>>
您不需要在构造函数中将方法分配给实例。这是 classes 已经工作的一部分。
这可以正常工作:
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 不需要自定义构造函数。只需将它声明为 class
,它就会有一个构造函数,您可以根据需要覆盖它。
顺便说一句,你最好用大写字母开头的名字来命名你的 class。用驼峰式命名方法更像是一种品味,但我觉得下划线更像 Pythonic - 但是大写绝对是可以使用的,以避免人们混淆对象和 classes.
我最近尝试进入 OOP 以迈向更高级的 python。我想在 class 中做一个函数列表。我从 而不是 使用 self.functionName = functionName
开始,这导致无法在列表中识别函数的错误。所以我假设你在 __init__
函数中编写的内容在 class 中作为全局函数工作,所以我将 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
>>>
您不需要在构造函数中将方法分配给实例。这是 classes 已经工作的一部分。
这可以正常工作:
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 不需要自定义构造函数。只需将它声明为 class
,它就会有一个构造函数,您可以根据需要覆盖它。
顺便说一句,你最好用大写字母开头的名字来命名你的 class。用驼峰式命名方法更像是一种品味,但我觉得下划线更像 Pythonic - 但是大写绝对是可以使用的,以避免人们混淆对象和 classes.