Classes and Objects

What's Class

A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state.

Class Syntax

  • Classes are created by keyword class

  • Attributes are the variables that belong to a class

  • Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute

class ClassName:
    Statement

Car Example 😂

class Car: 
    # attributes
    color = "red"
    body = "sedan"
    
    # methods
    def specs(self):
        print("car color is", self.color)
        print("body type is", self.body)


# Object instantiation
Bmw = Car()

# Accessing class attributes
# and method through objects
print(Bmw.color)
Bmw.specs()


Output:
red
car color is red
body type is sedan

The Self

  • The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

  • Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it.

  • If we have a method that takes no arguments, then we still have to have one argument.

__init__ Method

it's similar to constructors in C++ and Java

Constructors are used to initializing the object’s state. Like methods, a constructor also contains a collection of statements(i.e. instructions) that are executed at the time of Object creation. It runs as soon as an object of a class is instantiated. The method is useful to do any initialization you want to do with your object.

# A Sample class with init method
class Person:

	# init method or constructor
	def __init__(self, name):
		self.name = name

	# Sample Method
	def say_hi(self):
		print('Hello, my name is', self.name)

p = Person('Ayman')
p.say_hi()

Class and Instance Variables

Instance variables are for data, unique to each instance and class variables are for attributes and methods shared by all instances of the class. Instance variables are variables whose value is assigned inside a constructor or method with self whereas class variables are variables whose value is assigned in the class.

# Class for Dog
class Dog:
   
    # Class Variable
    animal = 'dog'            
   
    # The init method or constructor
    def __init__(self, breed, color):
     
        # Instance Variable    
        self.breed = breed
        self.color = color       
    
# Objects of Dog class
Rodger = Dog("Pug", "brown")
Buzo = Dog("Bulldog", "black")
 
print('Rodger details:')  
print('Rodger is a', Rodger.animal)
print('Breed: ', Rodger.breed)
print('Color: ', Rodger.color)
 
print('\nBuzo details:')  
print('Buzo is a', Buzo.animal)
print('Breed: ', Buzo.breed)
print('Color: ', Buzo.color)
 
# Class variables can be accessed using class
# name also
print("\nAccessing class variable using class name")
print(Dog.animal)

     
Output:
Rodger details:
Rodger is a dog
Breed:  Pug
Color:  brown

Buzo details:
Buzo is a dog
Breed:  Bulldog
Color:  black

Accessing class variable using class name
dog     

Modify Object Properties

You can modify properties on objects like this:

Bmw.color = "white"

Delete Object Properties

You can delete properties on objects by using the del keyword:

del Bmw.color

Delete Objects

You can delete objects by using the del keyword:

del Bmw

The pass Statement

class definitions cannot be empty, but if you for some reason have a class definition with no content, put in the pass statement to avoid getting an error.

class Person:
  pass

Last updated