Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting string in python with class members

Tags:

python

Consider this code:

class Foo:
  def geta(self):
    self.a = 'lie'
    return 'this is {self.a}'.format(?)

What should I write instead of the question mark so that the string will be formatted correctly?

like image 903
whomaniac Avatar asked Feb 04 '14 13:02

whomaniac


2 Answers

What you probably are looking for is

'this is {0.a}'.format(self)
'this is {.a}'.format(self)
'this is {o.a}'.format(o=self)
'this is {self.a}'.format(self=self)

Note, however, that you are missing at least a method in your class.

Directly under the class scope there is no such thing as self.

like image 77
glglgl Avatar answered Oct 22 '22 14:10

glglgl


The reference you include inside the brackets refers to either a number indicating the index of the argument passed to format, or a name directing to a named argument in the format call. Like that:

class Foo:
  def geta(self):
    self.a = 'lie'
    return 'this is {self.a}'.format(self=self)
like image 35
Cilyan Avatar answered Oct 22 '22 15:10

Cilyan