Programming a Class in Python

To define a class, it is similar to a function:

class [insert name of class here]():

Then underneath this attributes can be defined. A class constructor has to be used:

def __init__

Self must be then added to the brackets first, this is used so each individual object that is created using this class can keep hold of its own attributes over time - so the object can refer to its 'own data':

(self, [attributes here]):

Attributes are assigned to variables so they can be accessed throughout the object. 

(self, nationality = "British", gender = "male" ):
            self.nationality = nationality
            self.gender = gender

Once the attributes have been created, methods (functions of the class) can also be added, this example is what would be required to make the 'human object' speak:

def speak(self):
         print("Hello my gender is: ", self.gender)

Once the class has been created with attributes and methods, objects can be created from it. This is called instantiation. The following code is required:

jeremy = human()

This has created a human called Jeremy who is a British Male who can say "My Gender is Male". To get the object to output data more lines of code are required:


The new object created is accessing the attributes and methods declared in its class (its blueprint). 

Comments

Popular posts from this blog

CPU Fetch-Decode-Execute Cycle

Scheduling

Utility Software