Python Create a Class and Instantiate It

Document 对象参考手册Python3 Examples

In Python, a class is a blueprint or template for creating objects. By defining a class, we can create multiple objects with the same attributes and methods. Below is a simple example showing how to create a class and instantiate it.

Example

class Dog:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def bark(self):
        return f"{self.name} says woof!"

# Instantiate the class
my_dog = Dog("Buddy", 3)

# Access attributes and call methods
print(my_dog.name)
print(my_dog.age)
print(my_dog.bark())

Code explanation:

  1. class Dog:Defines a class namedDogthe class.
  2. def __init__(self, name, age):is the class constructor, used to initialize the object's attributes.selfRepresents the instance itself of the class,nameandageare the parameters passed to the constructor.
  3. self.name = nameandself.age = ageAssigns the passed parameters to the instance's attributes.
  4. def bark(self):Defines a method namedbarkmethod that returns a string representing the sound of a dog's bark.
  5. my_dog = Dog("Buddy", 3)Creates an instance of theDogclass and passes"Buddy"and3as parameters.
  6. print(my_dog.name)andprint(my_dog.age)Print the instance's attributes respectivelynameandage。
  7. print(my_dog.bark())Calls thebarkmethod and prints the returned string.

Output result:

Buddy
3
Buddy says woof!

Document 对象参考手册Python3 Examples

Other extensions