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.py116 chars7 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.py188 chars10 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