Home > Blockchain >  How to format strings in classes using attributes?
How to format strings in classes using attributes?

Time:03-17

I want to format an attribute-string of a class with another attribute of the same class like this:

class Test:
    def __init__(self):
        self.name = None
        self.full_name = 'name, {}'.format(self.name)

    def print_name(self):
        print(self.full_name)

my_object = Test()
my_object.name = 'my_object'

my_object.print_name()

Now it should print 'name, my_object' But it prints 'name, None'

What to do that the string formats with the assigned value of the object?

CodePudding user response:

You need to add full_name as a property so that you can add some more logic to it:

class Test:
    def __init__(self):
        self.name = None

    @property
    def full_name(self):
        return f'name, {self.name}'

    def print_name(self):
        print(self.full_name)


my_object = Test()
my_object.name = 'my_object'

my_object.print_name()

Resources:

  • Related