Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python format() pass one object

If i define the below custom class in Python:

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

Is there any way when using the string format() method to only have to pass in my object once and to then access that in all the arguments. Ideally I would like to be able to do something like this:

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

But I have to do this:

test_class = Test()
print "Hey {0.hey}, let's {1.yo}. Fo' {2.sho}".format(test_class, test_class, test_class)
like image 766
Peter Featherstone Avatar asked Sep 12 '26 13:09

Peter Featherstone


1 Answers

As you found out for yourself, you can use keyword arguments, but you don't even have to do that:

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

The 0 refers to the zeroth argument to format, the problem was you had no 1st and second argument, because you didn't need it.

Warning as an aside:

Also, since you seem to be coming to python from other languages, you might be making a common mistake. Note that the way you have defined your class;

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

uses only class-level variables, which will act like static members to borrow terminology from other languages. In other words, hey, yo, and fo are not instance attributes, although your instances have access to the class-level namespace. Check out this answer. Of course, this doesn't matter for the purposes of this question, but it can lead to bugs if you don't understand the semantics of the class definition.

like image 144
juanpa.arrivillaga Avatar answered Sep 15 '26 02:09

juanpa.arrivillaga



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!