【问题标题】:Can't print __str__ from the class无法从班级打印 __str__
【发布时间】:2022-01-03 14:16:51
【问题描述】:

我想知道如何打印特定索引的类内容。我创建了一个类,它包含某个地震运动的所有值,并将每个值存储在自己的数据类型中。

这是课程:

import re

class Txt_data:
       
    def __init__(self, result):
    
        self.date = result[0]
        self.time = result[1]
        self.latit = result[2]
        self.long = result[3]
        self.depth = result[4]
        self.md = result[5]
        self.ml = result[6]
        self.mw = result[7]
        self.region = result[8]
        self.method = result[9]    
  
    def date(self):
        return self._date

  
    def time(self):
        return self._time

  
    def latit(self):
        return self._latit

  
    def long(self):
        return self._long

  
    def depth(self):
        return self._depth

  
    def md(self):
        return self._md

  
    def ml(self):
        return self._ml

  
    def mw(self):
        return self._mw

  
    def region(self):
        return self._region

  
    def method(self):
        return self._method        

    # This does not work 
    def __str__(self):
        return ('MAG: ' + float(self.ml()) + ' DEPTH: ' + int(self.region()) + ' DATE/TIME: ' + str(self.date()) + ' ' + str(self.time()) + ' LAT: ' + float(self.latit()) + ' LON: ' + float(self.long()))

result = [('2021.12.02', '22:29:24', '36.9605', '28.1775', '13.0', '-.-', '1.5', '-.-', 'KARACA-MARMARIS (MUGLA)', ' Quick')]


print(Txt_data(result))

我尝试使用 str 方法打印数据,但它不起作用。

这是错误:

Traceback (most recent call last):
  File "/Users/seyfalsultanov/Documents/uni comp 100/comp100-2021f-ps5-seyfalku/main.py", line 73, in <module>
    print(Txt_data(result))
  File "/Users/seyfalsultanov/Documents/uni comp 100/comp100-2021f-ps5-seyfalku/main.py", line 60, in __str__
    print('MAG: ' + float(self.ml()) + ' DEPTH: ' + int(self.region()) + ' DATE/TIME: ' + str(self.date()) + ' ' + str(self.time()) + ' LAT: ' + float(self.latit()) + ' LON: ' + float(self.long()))
AttributeError: Txt_data instance has no __call__ method

我的问题是如何打印我尝试在课堂上使用 str 方法打印的字符串。 非常感谢。

【问题讨论】:

  • 您的实例属性正在隐藏同名的方法。例如,self.latit 是任何 result[2],而不是可调用方法。
  • 这些方法都不需要存在。只需直接访问实例属性,如果您找到引入 getter 的理由,您可以将实例属性替换为属性,而不会破坏类的公共接口。
  • 无论如何,发布的代码都不会产生该错误。我在self.time = result[1] 线上收到IndexError。将Txt_data(result) 替换为Txt_data(result[0]) 会得到预期的TypeError: 'str' object is not callable

标签: python string class printing return


【解决方案1】:

您的直接问题是您使用实例属性隐藏了所有方法,而不是为方法期望的属性使用_-前缀名称。

def __init__(self, result):

    self._date = result[0]
    self._time = result[1]
    self._latit = result[2]
    self._long = result[3]
    self._depth = result[4]
    self._md = result[5]
    self._ml = result[6]
    self._mw = result[7]
    self._region = result[8]
    self._method = result[9]    

但是,这些 getter 都不是必需的;直接使用实例属性即可。在 __str__ 中,使用 f 字符串执行任何必要的类型转换(您目前做错了;非 str 值需要转换为 str 值,而不是相反)。

class Txt_data:
       
    def __init__(self, result):
    
        self.date = result[0]
        self.time = result[1]
        self.latit = result[2]
        self.long = result[3]
        self.depth = result[4]
        self.md = result[5]
        self.ml = result[6]
        self.mw = result[7]
        self.region = result[8]
        self.method = result[9]    
  
    def __str__(self):
        return f'MAG: {self.ml} DEPTH: {self.region} DATE/TIME: {self.date} {self.time} LAT: {self.latit} LON: {self.long}'



result = ('2021.12.02', '22:29:24', '36.9605', '28.1775', '13.0', '-.-', '1.5', '-.-', 'KARACA-MARMARIS (MUGLA)', ' Quick')
print(Txt_data(result))

最后,我建议让__init__ 负责拆分列表。让它简单地接受 10 个不同的参数,并使用一个专用的类方法来解析一个固定格式的列表。

class Txt_data:
       
    def __init__(self, date, time, latitude, long, depth, md, ml, mw, region, method):
    
        self.date = date
        self.time = time
        self.latit = latit
        self.long = long
        self.depth = depth
        self.md = md
        self.ml = ml
        self.mw = mw
        self.region = region
        self.method = method

    @classmethod
    def from_list(cls, x):
        if len(x) != 10:
            raise ValueError("Wrong number of elements in list")
        return cls(*x)
  
    def __str__(self):
        return f'MAG: {self.ml} DEPTH: {self.region} DATE/TIME: {self.date} {self.time} LAT: {self.latit} LON: {self.long}'

【讨论】:

    【解决方案2】:

    我不知道你为什么单独创建所有这些方法,但我发现你的自变量与你的函数具有完全相同的名称,所以更改你的自变量名称(还记得在你有的地方更改变量名称返回它们中的每一个并从头开始删除破折号),删除“()” 从结果列表中,还从类的最终返回中删除 'float()' 和 'int()' 并用 'str()' 替换它们

    import re
    
    class Txt_data:
           
        def __init__(self, result):
        
            self.date1 = result[0]
            self.time1 = result[1]
            self.latit1 = result[2]
            self.long1 = result[3]
            self.depth1 = result[4]
            self.md1 = result[5]
            self.ml1 = result[6]
            self.mw1 = result[7]
            self.region1 = result[8]
            self.method1 = result[9]    
      
        def date(self):
            return self.date1
    
      
        def time(self):
            return self.time1
    
      
        def latit(self):
            return self.latit1
    
      
        def long(self):
            return self.long1
    
      
        def depth(self):
            return self.depth1
    
      
        def md(self):
            return self.md1
    
      
        def ml(self):
            return self.ml1
    
      
        def mw(self):
            return self.mw1
    
      
        def region(self):
            return self.region1
    
      
        def method(self):
            return self.method1     
    
        def __str__(self):
            return ('MAG: ' + str(self.ml()) + ' DEPTH: ' + str(self.region()) + ' DATE/TIME: ' + str(self.date()) + ' ' + str(self.time()) + ' LAT: ' + str(self.latit()) + ' LON: ' + str(self.long()))
    
    result = ['2021.12.02', '22:29:24', '36.9605', '28.1775', '13.0', '-.-', '1.5', '-.-', 'KARACA-MARMARIS (MUGLA)', ' Quick']
    
    
    print(Txt_data(result))
    

    我已经更正了你的代码,应该是这样的。

    【讨论】:

    • 为什么要在末尾添加1 而不是在前面添加_
    • 你知道为什么使用_吗?这是“私有”属性的约定(意味着它们不应该被用户直接访问),而且拥有一个任意数字比一个更有意义和中性的字符更烦人
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2017-09-17
    • 2016-02-22
    • 2021-12-24
    • 2019-05-08
    • 1970-01-01
    • 2017-07-28
    • 2021-09-11
    相关资源
    最近更新 更多