【问题标题】:Python OOP related to usage of instance variablesPython OOP 与实例变量的使用相关
【发布时间】:2018-03-10 08:39:09
【问题描述】:
class idk():
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def t(self):
        self.t = self.name + self.age
    def qrt(self):
        print(len(self.t))                             

abc = idk('abc','19')                 
abc.qrt()

abc.name= 'aduhd'            
abc.qrt()

当我运行此代码时,我收到以下错误

Traceback (most recent call last):
    File "C:/Users/Prajval/Desktop/test.py", line 11, in <module>
        abc.qrt()
    File "C:/Users/Prajval/Desktop/test.py", line 8, in qrt
        print(len(self.t))
TypeError: object of type 'instancemethod' has no len()

以下错误是什么意思:

TypeError: 'instancemethod' 类型的对象没有 len()

【问题讨论】:

  • 它给出了错误,因为变量't'不存在

标签: python-2.7 python-3.x class oop instance-variables


【解决方案1】:

您忘记调用该方法,您已将其同名t 作为实例变量。

def qrt(self):
    print(len(self.t()))

通过将方法命名为与实例变量相同的方法,您就是在玩火。当您第一次调用t 方法时,它将表现为一个方法,并在第一次调用后作为一个字符串。不要给自己挖坑让自己掉进去。

【讨论】:

    【解决方案2】:

    最终代码,

    class idk():
        def __init__(self,name,age):
            self.name = name
            self.age = age
            
        def t(self):
            self.t1 = self.name + self.age
            return self. t1 # was missing 
            
        def qrt(self):
            print(len(self.t()))                             
    
    abc = idk('abc','19')                 
    abc.qrt()
    
    abc.name= 'aduhd'            
    abc.qrt()
    
    5
    7
    
    [Program finished]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-12
      • 2017-11-09
      • 1970-01-01
      • 2012-10-12
      • 2015-12-01
      • 2014-09-21
      相关资源
      最近更新 更多