Python Create a Person Class with name and age Attributes
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
)
:
(
f
"Name: {self.name}, Age: {self.age}"
)
Create a Person object
person
=
Person
(
"Alice"
,
30
)
person.
display_info
(
)
Code analysis:
class Person:defines a class namedPerson.def __init__(self, name, age):is the class constructor, used to initialize the object's attributes.selfis a reference to the current object instance.self.name = nameandself.age = ageAssign the passed arguments to the object's attributes.def display_info(self):Defines a method used to print the object'snameandageattribute.person = Person("Alice", 30)Created aPersonan instance of the class, passing innameandagevalue.person.display_info()calleddisplay_infomethod to print out the object's attributes.
Output result:
Name: Alice, Age: 30
Python3 Examples