create a class with a name attribute that is displayed when an instance is printed in python

To create a class with a name attribute that is displayed when an instance is printed in python, you can define the class with an __init__ method and define the name attribute as an instance variable.

main.py
class Person:
    def __init__(self, name):
        self.name = name

person1 = Person("Alice")
print(person1.name)
116 chars
7 lines

In the example above, we define a Person class with an __init__ method that takes a name argument and assigns it to an instance variable self.name. To create an instance of the Person class, we pass a name argument to the class constructor, and assign the resulting instance to person1.

To display the name attribute when printing an instance of the Person class, we simply need to define the __str__ method for the class:

main.py
class Person:
    def __init__(self, name):
        self.name = name
        
    def __str__(self):
        return f"Person(name='{self.name}')"

person1 = Person("Alice")
print(person1)
188 chars
10 lines

In the updated example above, we define the __str__ method for the Person class to return a string representation of the instance. This method is called when any instance of the Person class is printed, allowing us to customize the output. Now when we print person1, we see the string "Person(name='Alice')".

gistlibby LogSnag