Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Creating a Class and Instantiating It

Python Creating a Class and Instantiating It

Document Object Reference Manual 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 analysis:

  1. class Dog: defines a class named Dog .
  2. def __init__(self, name, age): is the class constructor, used to initialize the object's attributes.self refers to the instance itself,name and age is the parameter passed to the constructor.
  3. self.name = name and self.age = age assigns the passed parameter to the instance attribute.
  4. def bark(self): defines a class named bark method that returns a string representing the sound a dog makes.
  5. my_dog = Dog("Buddy", 3) Created a Dog class, passing in "Buddy" and 3 as its argument.
  6. print(my_dog.name) and print(my_dog.age) print the instance attributes separately name and age。
  7. print(my_dog.bark()) called bark method and print the returned string.

Output result:

Buddy
3
Buddy says woof!

Document Object Reference Manual Python3 Examples