create a class person: with __str__ in python

To create a class person with str method in Python, we can define the class as follows:

main.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __str__(self):
        return f"{self.name}, {self.age} years old"
177 chars
8 lines

Here, we define a class called Person with a constructor that takes two arguments, name and age. We then define the str method that returns a string representation of the Person object.

To use this class, we can create a new instance of it and print it:

main.py
p1 = Person("John", 30)
print(p1)  # Output: John, 30 years old
64 chars
3 lines

Here, we create a new instance of the Person class with the name "John" and age 30. We then print the object using the print function, which calls the str method and outputs the string representation of the object.

gistlibby LogSnag