【问题标题】:Something incomprehensible to the class课堂上无法理解的东西
【发布时间】:2021-08-13 23:21:02
【问题描述】:

班级无法理解的事情。

   From aiogram.types import InputFile
   
   a = InputFile(r'C:\Users\Acer\Desktop\f\1.mp3')
   b = InputFile(r'C:\Users\Acer\Desktop\f\2.mp3')
   c = InputFile(r'C:\Users\Acer\Desktop\f\3.mp3')
   d = InputFile(r'C:\Users\Acer\Desktop\f\4.mp3')
   e = InputFile(r'C:\Users\Acer\Desktop\f\5.mp3')
   
   class Make:
       def __init__(self, art, zanr, name, put):
       self.art = art
       self.zanr = zanr
       self.name = name
       self.put = put
   
   a1 = Make('Blaze', 'Hip-hop', 'Music_1234', a)
   b1 = Make('PORCHY', 'Rap', 'Trak_28', b)
   c1 = Make('Blaze', 'Pop', 'North-abc', c)
   d1 = Make('PORCHY', 'Hip-hop', '26-83', d)
   e1 = Make('Blaze', 'Pop', 'Abnov', e)
   
   spis = [a1, b1, c1, d1, e1]
   
   for x in range(0, 4):
       if spis[x].art == 'PORCHY':
           print(cl.spis[x].put)

控制台:

<InputFile 'attach://GqEaqV-Wj3zekeFP9GIygA' with file='<_io.BufferedReader name='C:\\Users\\Acer\\Desktop\\f\\2.mp3'>'>
<InputFile 'attach://JeYgSuIUgVjS7nDwPONivQ' with file='<_io.BufferedReader name='C:\\Users\\Acer\\Desktop\\f\\4.mp3'>'>

为什么不呢:

C:\Users\Acer\Desktop\f\2.mp3
C:\Users\Acer\Desktop\f\4.mp3

【问题讨论】:

  • 如果您指的是双反斜杠,这很可能是通过BufferedReader.__repr__ 使用str.__repr__ 来生成文件名的表示的结果。跨度>
  • 不,为什么不直接返回变量“a”的值,格式为:C:\Users\Acer\Desktop\f\2.mp3。如何让它像这样返回?
  • 因为put 属性是一个InputFile 实例,而不仅仅是一个文件名。您必须查看InputFile 的定义,才能了解为什么它的__str__ 方法(或者可能是__repr__ 方法)是这样定义的。
  • 换句话说,它显示变量a的值;该值不是str 对象。

标签: python class oop import python-class


【解决方案1】:

通过查看InputFile source code,您可以看到__str__ 方法的定义如下:

def __str__(self):
        return f"<InputFile 'attach://{self.attachment_key}' with file='{self.file}'>"

并且__repr__ 方法等于__str__

如果您只想打印文件的路径,我相信您应该使用

print(cl.spis[x].put.get_filename())

【讨论】:

  • 谢谢,但是控制台输出是这样的:2.mp3 4.m​​p3 我需要这样的:C:\Users\Acer\Desktop\f\2.mp3 C:\Users\Acer \Desktop\f\4.mp3 我试着这样写: print (r'C:\Users\Acer\Desktop\f\ '+ cl.spis [x] .put.get_filename ()) Python认为cl.spis [x] .put.get_filename 为文本并显示错误,您能告诉我如何解决吗?
  • 导入操作系统后尝试print(os.path.realpath( cl.spis[x].put.get_file().name) )
  • 再次感谢,但问题又来了,这个文件的路径被传递给机器人,然后发送给用户,我试过这样:a = os.path.realpath (cl.spis [x] .put.get_file (). name) print (os.path.realpath (cl.spis [x] .put.get_file (). name)) await bot.send_audio (chat_id = id, audio = a) 所以:print (os.path.realpath (cl.spis [x] .put.get_file (). name)) await bot.send_audio (chat_id = id, audio = os.path.realpath (cl.spis [x] .put.get_file (). name))但这是错误:
猜你喜欢
  • 2020-02-21
  • 2017-05-11
  • 2019-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多