在实例化新类时Python会返回什么?

时间:2010-12-16 14:05:24

标签: python oop class

在实例化一个新类时,我发现了很多关于Python的怪癖。我确定这只是因为我不熟悉这种语言,但即便如此,我能看到的行为真的很奇怪。

如果我打开iPython并输入以下内容:

class Person:
    def __init__(self, name):
        self.name = name

    def hello(self):
        print "Hello, " + self.name

一切都像我期望的那样完成:

In [2]: Person
Out[2]: <class __main__.Person at 0x1c97330>

In [3]: p = Person("Jamie")

In [4]: p
Out[4]: <__main__.Person instance at 0x1c90b98>

In [5]: p.hello()
Hello, Jamie

然而,如果我然后访问一个单独的类内部包 - 没有什么太花哨,我可能会添加 - 并实例化一个新类,这一切都出错了。 {strong> palestrina / cache.py

Here's the link to the code
In [6]: from palestrina.cache import Cache

In [7]: Cache
Out[7]: <class palestrina.cache.Cache at 0x1c97750>

In [8]: c = Cache(application = 'example', backend = 'filesystem')

In [9]: c
Out[9]: ---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/Users/jamierumbelow/Sites/Os/palestrina/<ipython console> in <module>()

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/IPython/Prompts.pyc in __call__(self, arg)
    550 
    551             # and now call a possibly user-defined print mechanism

--> 552             manipulated_val = self.display(arg)
    553 
    554             # user display hooks can change the variable to be stored in


/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/IPython/Prompts.pyc in _display(self, arg)
    576             return IPython.generics.result_display(arg)
    577         except TryNext:
--> 578             return self.shell.hooks.result_display(arg)
    579 
    580     # Assign the default display method:


/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/IPython/hooks.pyc in __call__(self, *args, **kw)
    139             #print "prio",prio,"cmd",cmd #dbg

    140             try:
--> 141                 ret = cmd(*args, **kw)
    142                 return ret
    143             except ipapi.TryNext, exc:

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/site-packages/IPython/hooks.pyc in result_display(self, arg)
    169 
    170     if self.rc.pprint:
--> 171         out = pformat(arg)
    172         if '\n' in out:
    173             # So that multi-line strings line up with the left column of


/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pprint.pyc in pformat(self, object)
    109     def pformat(self, object):
    110         sio = _StringIO()
--> 111         self._format(object, sio, 0, 0, {}, 0)
    112         return sio.getvalue()
    113 

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pprint.pyc in _format(self, object, stream, indent, allowance, context, level)
    127             self._readable = False
    128             return
--> 129         rep = self._repr(object, context, level - 1)
    130         typ = _type(object)
    131         sepLines = _len(rep) > (self._width - 1 - indent - allowance)

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pprint.pyc in _repr(self, object, context, level)
    221     def _repr(self, object, context, level):
    222         repr, readable, recursive = self.format(object, context.copy(),
--> 223                                                 self._depth, level)
    224         if not readable:
    225             self._readable = False

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pprint.pyc in format(self, object, context, maxlevels, level)
    233         and whether the object represents a recursive construct.
    234         """
--> 235         return _safe_repr(object, context, maxlevels, level)
    236 
    237 

/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/pprint.pyc in _safe_repr(object, context, maxlevels, level)
    318         return format % _commajoin(components), readable, recursive
    319 
--> 320     rep = repr(object)
    321     return rep, (rep and not rep.startswith('<')), False
    322

TypeError: 'bool' object is not callable

我无法理解这里发生了什么。有人可以向我解释可能会发生什么吗?

感谢。

2 个答案:

答案 0 :(得分:4)

好吧,您删除了相关部分(追溯)并将其替换为粘贴中的...

但看起来你在班级的表现方面有错误。

以下是错误的模拟:

>>> class MyClass(object):
...     def __repr__(self):
...         return True()
...
>>> c = MyClass()
>>> c

请检查您删除的追溯,然后您会看到确切的结果。如果您不能,请编辑您的问题并将其包含在内,以便我们进一步解释。

提供该类的源代码也会有所帮助。

答案 1 :(得分:1)

不是Python的错,你的软件包造成了麻烦。

你使用一些讨厌的技巧来节省打字。具体来说,您将覆盖特殊__getattr__方法,该方法在您尝试访问c属性时使用。检查它会查找__repr__方法,方法是属性,所以......

为方便起见,试图完全替换类的属性是一个非常糟糕的主意。我认为您最好使用__getitem____setitem____delitem__,因此您的缓存访问权限类似于c["name"]而不是c.name

编辑:另一个提示,尽量不要抓住所有错误,除非你有一些富有成效的事情要做。如果你没有在get()上捕获keyerrors并将它们转换为return False,那么回溯就会显示它正在尝试做什么。如果我想在缓存中存储True或False怎么办?我怎么知道False是否意味着错误或“价值缺失”?