Skip to main content
 首页 » 编程设计

python之如何访问类范围内的 "self"

2025年05月04日11findumars

我遇到了一个有趣的问题。

假设我们有一个类,在它的构造函数中我们将一个 bool 值作为参数。如何根据实例的条件/ bool 值在类中定义方法?例如:

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." 

请您参考如下方法:

你不能,但你可以定义不同名称的方法,并在特定情况下公开它们。例如:

class X(object): 
    def __init__(self, flag): 
        if flag: 
            self.method = self._method 
 
    def _method(self): 
        print "I'm a method!" 

测试它:

>>> X(True).method() 
I'm a method! 
>>> X(False).method() 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
AttributeError: 'X' object has no attribute 'method'