如何访问“自我”里面的类的范围? [英] How to access "self" inside the scope of a class?

查看:137
本文介绍了如何访问“自我”里面的类的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've crossed an interesting problem.

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

Suppose we have a class, and in its constructor we take a boolean as an argument. How can I define methods inside the class based on the instance's condition/boolean? For example:

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


推荐答案

不同的名字,并在某些情况下暴露。例如:

You can't, but you can define methods with different names and expose them under certain circumstances. For example:

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'

这篇关于如何访问“自我”里面的类的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆