2

Not sure if this is possible in Python, but I'd like to have an instance of a class as a module-level global variable that, when called, returns a default property.

The idea comes from this question that overrides __call__ to have a class mimic a function.

Quick (untested) example of the idea:

class _foo(object):
    __slots__ = ("_foo",)
    _init = False

    def __init__(self):
        if not _init:
            self._foo = ["bar", "baz", "zog"]

    def __call__(self, item=None):
        if itme is not None:
            return self._foo[item]
        else:
            return self._foo

    def __getitem__(self, item):
        return self._foo[item]

# Module level
FOO = _foo()



Assume the above code is in a module (foo.py). Using the interpreter, I cal get the callable form to work how I want, but not the non-callable form.

>>> import foo

# callable forms
>>> foo.FOO(0)
"bar"
>>> foo.FOO()
["bar", "baz", "zog"]

# attribute forms
>>> foo.FOO[2]
"zog"

# doesn't work
>>> foo.FOO
<foo._foo object at 0xdeadbeef>

# desired output
>>> foo.FOO
["bar", "baz", "zog"]



My thinking is that I need to define a default property somehow so that when calling the instance directly, I get the internal list/dict of my choosing. I could cheat and do this via overriding repr, but that kinda breaks Python's own API and I want to avoid that. Passing no value in square brackets (>>> foo.FOO[]) yields a syntax error instead.

I'd like any potential solutions to be compatible with Python 2.4 at minimum and 2.7 at maximum. If this isn't possible, then I guess I'll just stick to using the callable format.

4

3 に答える 3

3

これは無理です、ごめんなさい。foo.FOO呼び出し可能 (_fooインスタンス) と純粋なリスト オブジェクトの両方になることはできません。

もちろん「無添加」と言いました。卑怯だと思ったら…

class _foo(list):
    _init = False
    def __init__(self):
        if self._init:
            list.__init__(self)
        else:
            list.__init__(self, ['bar', 'baz', 'zog'])

    def __call__(self, item=None):
        if item is None:
            return self
        return self[item]

FOO = _foo()

使用法:

>>> FOO()
['bar', 'baz', 'zog']
>>> FOO(0)
'bar'
>>> FOO
['bar', 'baz', 'zog']
于 2012-09-18T01:21:47.803 に答える
1

今のところ、別のモジュール内でこれを試すと、 FOO がモジュール内に存在しないという AttirbuteError が発生します。モジュールをインポートするこのコードは、私にとっては正しく機能します。

import foo
FOO2 = foo.FOO
print(FOO2())
print(FOO2(1))

パイソン 2.7.3

于 2012-09-18T01:13:50.527 に答える
0

クラスで定義__repr__(self)して、そのインスタンスが Python インタープリターでどのように表示されるかを定義します。この場合、おそらくreturn repr(self._foo).

于 2012-09-18T00:28:00.670 に答える