Python Create a Class and Instantiate It
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())
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:
class Dog:Defines a class namedDogthe class.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.self.name = nameandself.age = ageAssigns the passed parameters to the instance's attributes.def bark(self):Defines a method namedbarkmethod that returns a string representing the sound of a dog's bark.my_dog = Dog("Buddy", 3)Creates an instance of theDogclass and passes"Buddy"and3as parameters.print(my_dog.name)andprint(my_dog.age)Print the instance's attributes respectivelynameandage。print(my_dog.bark())Calls thebarkmethod and prints the returned string.
Output result:
Buddy 3 Buddy says woof!Other extensions
Python3 Examples