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

Python Create a Person Class with name and age Attributes

Python Create a Person Class with name and age Attributes

Document Object Reference Manual Python3 Examples

We will create a simple Person class that contains two attributes:name and age. We will define a constructor for this class to initialize these attributes and add a method to print them.

Example

class

Person:

   

def

init

(

self

,

name

,

age

)

:

       

self

.

name

=

name

       

self

.

age

=

age

   

def

display_info

(

self

)

:

       

print

(

f

"Name: {self.name}, Age: {self.age}"

)

Create a Person object

person

=

Person

(

"Alice"

,

30

)

person.

display_info

(

)

Code analysis:

  1. class Person: defines a class named Person .
  2. def __init__(self, name, age): is the class constructor, used to initialize the object's attributes.self is a reference to the current object instance.
  3. self.name = name and self.age = age Assign the passed arguments to the object's attributes.
  4. def display_info(self): Defines a method used to print the object's name and age attribute.
  5. person = Person("Alice", 30) Created a Person an instance of the class, passing in name and age value.
  6. person.display_info() called display_info method to print out the object's attributes.

Output result:

Name: Alice, Age: 30

Document Object Reference Manual Python3 Examples