Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement a Person Class That Supports Updating Name and Age

Python Implement a Person Class That Supports Updating Name and Age

Document Object Reference Manual Python3 Examples

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

)

print

(

person

)

person.

update_name

(

"Bob"

)

person.

update_age

(

25

)

print

(

person

)

Code analysis:

  1. __init__ The method is the class constructor, used to initialize Person an instance of the class. It takes two parameters:name and age, and assigns them to the instance variables self.name and self.age。
  2. update_name The method updates the name attribute. It takes one parameter new_name, and assigns it to self.name。
  3. update_age The method updates the age attribute. It takes one parameter new_age, and assigns it to self.age。
  4. __str__ The method returns a string representation of the Person object, making it easy to print.

Output result:

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

Document Object Reference Manual Python3 Examples