Python implements a Person class, supporting updating name and age
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)
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:
__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。update_nameThe method is used to updatenameattribute. It accepts one parameternew_name, and assigns it toself.name。update_ageThe method is used to updateageattribute. It accepts one parameternew_age, and assigns it toself.age。__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)Other extensions
Python3 Examples