【发布时间】:2014-04-05 14:36:46
【问题描述】:
我遇到了一个有趣的问题。
假设我们有一个类,并且在它的构造函数中我们将一个布尔值作为参数。如何根据实例的条件/布尔值在类中定义方法?例如:
class X():
def __init__(self, x):
self.x = x
if self.x == true: # self is unreachable outside a method.
def trueMethod():
print "The true method was defined."
if self.x == false: # self is unreachable outside a method.
def falseMethod():
print "The false method was defined."
【问题讨论】:
-
你为什么要这样做?似乎只会让用户感到困惑。
-
self在其他语言中类似于this。它只能使用实例方法访问。 -
在构造函数中定义你的方法。如果您希望它们成为方法,请给它们一个 self 参数。
-
@JayanthKoushik 我已经在 BrenBarn 的问题中解释了我为什么要这样做。
标签: python class scope instance self