Python Creating a Class and Instantiating 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
(
my_dog.
name
)
(
my_dog.
age
)
(
my_dog.
bark
(
)
)
Code analysis:
class Dog:defines a class namedDog.def __init__(self, name, age):is the class constructor, used to initialize the object's attributes.selfrefers to the instance itself,nameandageis the parameter passed to the constructor.self.name = nameandself.age = ageassigns the passed parameter to the instance attribute.def bark(self):defines a class namedbarkmethod that returns a string representing the sound a dog makes.my_dog = Dog("Buddy", 3)Created aDogclass, passing in"Buddy"and3as its argument.print(my_dog.name)andprint(my_dog.age)print the instance attributes separatelynameandage。print(my_dog.bark())calledbarkmethod and print the returned string.
Output result:
Buddy
3
Buddy says woof!
Python3 Examples