Python create a Person class with attributes name and age
We will create a simplePersonclass that contains two attributes:nameandage. We will define a constructor for this class to initialize these attributes, and add a method to print these attributes.
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()
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 explanation:
class Person:Defines a class namedPersonclass.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 = ageAssigns the passed parameters to the object's attributes.def display_info(self):Defines a method to print the object'snameandageattributes.person = Person("Alice", 30)Creates anPersoninstance of the class, and passes innameandagethe values.person.display_info()Call thedisplay_infomethod, which prints the object's attributes.
Output result:
Name: Alice, Age: 30Other extensions
Python3 Examples