Python Syntax for Classes and Objects 


In this section, we will review the Python classes and objects that are related to clarify the coding syntax used in the Mind Map example. As we mentioned previously, you don't have to worry about syntax and can focus your introduction on images, diagrams, or a timeline. But if you would like to look at the details of what a potential CSInstructor class would look like, and how methods (functions) and properties (variables are used), we included some code snippets below.

Python is object-oriented, it uses objects and classes to organize code:


Classes have some pre-defined methods that we can override. Below are the typical behaviors for two of these functions along with the special keyword self:

__init__  constructor method; is called when an object is created; it is used to initialize attributes of the object

__str__  string method; it is called when an object is printed; returns a representation of the object as a string

self: special keyword that refers to the current object

Here is a possible implementation of the CSInstructor class.

class CSInstructor:
def __init__(self, name):
self.name = name

def __str__(self):
output = "Name: "+ self.name + "\n"
output += "family info, number of kids: "+ str(self.numberKids)
return output
def set_familyInfo(self, numberKids):
self.numberKids = numberKids


# creating an instance of the class
me = CSInstructor("CS Learner")
me.set_familyInfo(2) # calling a method
print(me) # printing the object will use the __str__ method

       

You may experiment with the code above and practice with creating your own instances of the class and adding your print statements in the code embed below.  

Note: Your work will not be saved when you leave the page. Please copy and paste the code you entered in a text file or on a new page in your Digital Portfolio document.

Additional methods and attributes that can be added to our class.

    def set_thingsILove(self, item1, BBQ = True):
        self.lovesBest = item1
        self.loveBBQ = BBQ
  
    def set_stateHistory(self, states):
        self.statesLivedIn = states

# the above methods can be used on an instance as shown below
me.set_thingsILove("the beach", False)
me.set_stateHistory(["Michigan", "Texas"])