Creating a Class

How do we create a class?

To create a class, we can use the class keyword to define the data structures (attributes) and methods (behaviours or operations that can act on the data structures of that object):

1. Class Definition

class class_name:
	...
	# Use 'pass' as a placehodler if the class body is  empty for now

Optional docstring

We can provide an additional docstring after the class definition to provide information about the class.

class <class_name>:
	'''<optional_docstring>'''

2. Adding a Constructor (__init__) Method

Define the __init__ method within the class to initialize and define the attributes when an object is created. This method is called a constructor:

class ClassName:
	''' Optional doc string of the class'''

    def __init__(self, attribute1, attribute2, ...):
        # Initialize attributes: self.instance_var
        self.attribute1 = attribute1 #initial value for attribute1 passed
        self.attribute2 = attribute2 #initial value for attribute2 passed
        # ...
Defining default values

You can provide default values for attributes in the __init__ method. This allows creating objects with some attributes set to default values if they are not explicitly provided during object creation

class Rectangle:
    def __init__(self, length=0, width=0): # defining default values
        self.length = length # length = 0 if no other value is specified by user
        self.width = width

3. Adding a Behaviours to a Class

To define methods within the class to represent the behaviors or actions that objects can perform, we can follow the process of creating a user-defined functions. Note: self is passed as the first parameter explicitly every single time we define a method.

class ClassName:
	''' Optional doc string of the class'''

    def __init__(self, attribute1, attribute2, ...):
        # Initialize attributes: self.instance_var
        self.attribute1 = attribute1 #initial value for attribute1 passed
        self.attribute2 = attribute2 #initial value for attribute2 passed
        # ...

	# Defining methods
	def function_name(self, param1, param2,...):
		# body of function

4. Constructing an Instance of the Object

Create instances (objects) of the class by calling the class as if it were a function. This creates the class object stored in the variable in which it is assigned to:

obj_name = ClassName(0)

The variable essentially points to the template in memory (created via class keyword) and is used to access the code and data for that particular instance of the class .

Accessing Attributes and Invoking Methods

To invoke a method of the class, we use the dot notation to call the method for that object as defined in the class:

obj_name.method()

Use dot notation to access attributes:

obj_name.attribute1
Powered by Forestry.md