gpt4 book ai didi

Python format() 传递一个对象

转载 作者:太空宇宙 更新时间:2023-11-03 12:13:40 24 4
gpt4 key购买 nike

如果我在 Python 中定义以下自定义类:

class Test:
hey = 'ho'
yo = 'go'
fo = 'sho'

在使用字符串 format() 方法时,有什么办法只需要传入我的对象一次,然后在所有参数中访问它。理想情况下,我希望能够做这样的事情:

test_class = Test()
print "Hey {0.hey}, let's {1.yo}. Fo' {2.sho}".format(test_class)

但我必须这样做:

test_class = Test()
print "Hey {0.hey}, let's {1.yo}. Fo' {2.sho}".format(test_class, test_class, test_class)

最佳答案

正如您自己发现的那样,您可以使用关键字参数,但您甚至不必这样做:

In [4]: print("Hey {0.hey}, let's {0.yo}. Fo' {0.fo}".format(t))
Hey ho, let's go. Fo' sho

In [5]: class Test:
...: hey = 'ho'
...: yo = 'go'
...: fo = 'sho'
...:

In [6]: t = Test()

In [7]: print("Hey {0.hey}, let's {0.yo}. Fo' {0.fo}".format(t))
Hey ho, let's go. Fo' sho

0 指的是 formatzeroth 参数,问题是你没有第一个和第二个参数,因为你 不需要它

旁白警告:

此外,由于您似乎是从其他语言转向 Python,因此您可能犯了一个常见错误。请注意您定义类的方式;

class Test:
hey = 'ho'
yo = 'go'
fo = 'sho'

仅使用类级别 变量,这些变量将像静态成员 一样从其他语言借用术语。换句话说,heyyofo 不是实例属性,尽管您的实例可以访问类级命名空间。查看this answer .当然,这对于这个问题的目的来说并不重要,但如果您不理解类定义的语义,它可能会导致错误。

关于Python format() 传递一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45512735/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com