Python Implement a Person Class That Supports Updating Name and Age
We will create a simple Person class that contains two attributes:name and age. We will add two methods to this class:update_name and update_age, used to update name and age attribute.
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
)
(
person
)
person.
update_name
(
"Bob"
)
person.
update_age
(
25
)
(
person
)
Code analysis:
__init__The method is the class constructor, used to initializePersonan instance of the class. It takes two parameters:nameandage, and assigns them to the instance variablesself.nameandself.age。update_nameThe method updates thenameattribute. It takes one parameternew_name, and assigns it toself.name。update_ageThe method updates theageattribute. It takes one parameternew_age, and assigns it toself.age。__str__The method returns a string representation of thePersonobject, making it easy to print.
Output result:
Person(name=Alice, age=30)
Person(name=Bob, age=25)
Python3 Examples