1

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?

0

1 Answer 1

2

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:

Sign up to request clarification or add additional context in comments.

2 Comments

print_name() is quite useless there though.
@OlvinRoght I guess, but it is the same useful as in the OP's code, for example, they also could just use print(self.full_name) or the print_name function could be the one that creates this string or it could be created using __str__ or sth else, but as for learning this is fine, after all their question was about formatting strings using attributes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.