如何在类的范围内访问“self”?

2024-03-06

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

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

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'
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在类的范围内访问“self”? 的相关文章

随机推荐