Python implements a Person class, supporting updating name and age

Document 对象参考手册Python3 Examples

We will create a simplePersonclass, which contains two attributes:nameandage. We will add two methods to this class:update_nameandupdate_age, used to updatenameandageattribute.

Example

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

    def update_name(self, new_name):
        self.name = new_name

    def update_age(self, new_age):
        self.age = new_age

    def __str__(self):
        return f"Person(name={self.name}, age={self.age})"

# Example usage
person = Person("Alice", 30)
print(person)

person.update_name("Bob")
person.update_age(25)
print(person)

Code analysis:

  1. __init__The method is the constructor of the class, used to initializePersonan instance of the class. It accepts two parameters:nameandage, and assigns them to instance variables respectivelyself.nameandself.age。
  2. update_nameThe method is used to updatenameattribute. It accepts one parameternew_name, and assigns it toself.name。
  3. update_ageThe method is used to updateageattribute. It accepts one parameternew_age, and assigns it toself.age。
  4. __str__The method is used to returnPersonthe string representation of the object, convenient for printing output.

Output result:

Person(name=Alice, age=30)
Person(name=Bob, age=25)

Document 对象参考手册Python3 Examples

Other extensions