【问题标题】:UserString subclass, 'str' object is not callableUserString 子类,'str' 对象不可调用
【发布时间】:2016-01-31 23:26:06
【问题描述】:

我有点卡在这段代码上,它应该创建一个类似字符串的对象,该对象在使用时将返回内部 lambda 的值。我使用 collections.UserString。

from collections import UserString
class instrx(UserString):
    func = None
    data = ''
    def __init__(self,func):
        self.func = func
    def __getattribute__(self,name):
        print("get",name)
        if name=='data':
            self.data = self.func()
        return UserString.__getattribute__(self,name)
a = instrx(lambda: 'aa')
print(a,type(a))
print(a.lower())

运行这段代码给了我这个:

Traceback (most recent call last):
  File "C:\path\a.py", line 14, in <module>
    print(a.lower())
  File "C:\Python35\lib\collections\__init__.py", line 1082, in __str__
    def __str__(self): return str(self.data)
  File "C:\path\a.py", line 10, in __getattribute__
    self.data = self.func()
TypeError: 'str' object is not callable

Python 版本:3.4、3.5。

【问题讨论】:

    标签: python python-3.x collections


    【解决方案1】:

    好的,我想通了。 似乎在 UserString 中的某些函数(例如 .lower() 示例)中使用了 self.__class__(self.data) 构造。我做了一些解决方法:

    import time
    from collections import UserString
    class instrx(UserString):
        func = None
        data = ''
        def __init__(self,data,func=None):
            self.data = data
            if func==None:
                self.func = lambda: UserString.__getattribute__(self,'data')
            else:
                self.func = func
        def __getattribute__(self,name):
            if name=='data':
                self.data = str(self.func())
            return UserString.__getattribute__(self,name)
    a = instrx('',func=lambda: time.time())
    print(a,type(a))
    print(a.lower())
    print(a+"test")
    

    工作得很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 2011-06-07
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多