Python create a Person class with attributes name and age

Document 对象参考手册Python3 Examples

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()

Code explanation:

  1. class Person:Defines a class namedPersonclass.
  2. def __init__(self, name, age):Is the class constructor, used to initialize the object's attributes.selfIs a reference to the current object instance.
  3. self.name = nameandself.age = ageAssigns the passed parameters to the object's attributes.
  4. def display_info(self):Defines a method to print the object'snameandageattributes.
  5. person = Person("Alice", 30)Creates anPersoninstance of the class, and passes innameandagethe values.
  6. person.display_info()Call thedisplay_infomethod, which prints the object's attributes.

Output result:

Name: Alice, Age: 30

Document 对象参考手册Python3 Examples

Other extensions