CS.QIAU - Winter 2020 PYTHONObject-Oriented - Session 8 Omid AmirGhiasvand Programming
PROGRAMMING IS A TYPE OF IMPERATIVE PROGRAMMING PARADIGM OBJECT-ORIENTED Objects are the building blocks of an application
IMPERATIVE PROGRAMMING IS A PROGRAMMING PARADIGM THAT USES STATEMENTS THAT CHANGE A PROGRAM’S STATE.
DECLARATIVE PROGRAMMING IS A PROGRAMMING PARADIGM THAT EXPRESSES THE LOGIC OF A COMPUTATION WITHOUT DESCRIBING ITS CONTROL FLOW.
IMPERATIVE VS. DECLARATIVEHuge paradigm shift. Are you ready?
Object-Oriented Programming ▸ The basic idea of OOP is that we use Class & Object to model real-world things that we want to represent inside our programs. ▸ Classes provide a means of bundling “data” and “behavior” together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Programming or Software Engineering
OBJECT an object represents an individual thing and its method define how it interacts with other things A CUSTOM DATA TYPE CONTAINING BOTH ATTRIBUTES AND METHODS
CLASS objects are instance of classes IS A BLUEPRINT FOR THE OBJECT AND DEFINE WHAT ATTRIBUTES AND METHODS THE OBJECT WILL CONTAIN
OBJECTS ARE LIKE PEOPLE. THEY ARE LIVING, BREATHING THINGS THAT HAVE KNOWLEDGE INSIDE THEM ABOUT HOW TO DO THINGS AND HAVE MEMORY INSIDE THEM SO THEY CAN REMEMBER THINGS. AND RATHER THAN INTERACTING WITH THEM AT A VERY LOW LEVEL, YOU INTERACT WITH THEM AT A VERY HIGH LEVEL OF ABSTRACTION, LIKE WE’RE DOING RIGHT HERE. HERE’S AN EXAMPLE: IF I’M YOUR LAUNDRY OBJECT, YOU CAN GIVE ME YOUR DIRTY CLOTHES AND SEND ME A MESSAGE THAT SAYS, “CAN YOU GET MY CLOTHES LAUNDERED, PLEASE.” I HAPPEN TO KNOW WHERE THE BEST LAUNDRY PLACE IN SAN FRANCISCO IS. AND I SPEAK ENGLISH, AND I HAVE DOLLARS IN MY POCKETS. SO, I GO OUT AND HAIL A TAXICAB AND TELL THE DRIVER TO TAKE ME TO THIS PLACE IN SAN FRANCISCO. I GO GET YOUR CLOTHES LAUNDERED, I JUMP BACK IN THE CAB, I GET BACK HERE. I GIVE YOU YOUR CLEAN CLOTHES AND SAY, “HERE ARE YOUR CLEAN CLOTHES.” YOU HAVE NO IDEA HOW I DID THAT. YOU HAVE NO KNOWLEDGE OF THE LAUNDRY PLACE. MAYBE YOU SPEAK FRENCH, AND YOU CANNOT EVEN HAIL A TAXI. YOU CANNOT PAY FOR ONE, YOU DO NOT HAVE DOLLARS IN YOUR POCKET. YET I KNEW HOW TO DO ALL OF THAT. AND YOU DIDN’T HAVE TO KNOW ANY OF IT. ALL THAT COMPLEXITY WAS HIDDEN INSIDE OF ME, AND WE WERE ABLE TO INTERACT AT A VERY HIGH LEVEL OF ABSTRACTION. THAT’S WHAT OBJECTS ARE.THEY ENCAPSULATE COMPLEXITY, AND THE INTERFACES TO THAT COMPLEXITY ARE HIGH LEVEL. Do you know who give this description?
Object-Oriented Benefits ▸ Much more easier to maintain. ▸ Code Reuse. ▸ Cleaner Code. ▸ Better Architecture. ▸ Abstraction. ▸ Fewer Faults. Why? Fault Error Failure Fault-Tolerance Error MaskingHere we are Programming or Software Engineering
Definition of the Class ▸ A Class is a Template or Blueprint which is used to instantiate objects. Include: ▸ Data/Attributes/Instance variable ▸ Behavior/Methods ▸ An Object refer to particular instance of a class where the object contains instance variables (attributes) and methods defined in the class. attributes Methods The act of creating object from class is called instantiation
O B J E C T ’ S AT T R I B U T E S REPRESENT THE STATE OF THE THING WE TRY TO MODEL. data == attributes == instance variables != class variables
Object-Oriented Basic Concepts Encapsulation Inheritance Polymorphism
Encapsulation Concept ▸ Encapsulation is the process of combining attributes and methods that work on those attributes into a single unit called class. ▸ Attributes are not accessed directly; it is accessed through the methods present in the class. ▸ Encapsulation ensures that the object’s internal representation (its state and behavior) are hidden from the rest of the application attributes Methods Information and implementation hiding
PYTHON SUPPORT OBJECT-ORIENTED
Creating a Class ▸ Classes are defined by using class keyword, followed by ClassName and a colon. ▸ Class definition must be executed before instantiating an object from it. class ClassName : def __init__(self,parameter_1,parameter_2,…): self.attribute_1 = parameter_1 … def method_name(self,parameter_1, …): statement-1 class constructor - initializing object
Example of Creating a Class ▸ Creating a Class for Dog - Any dog 1. class Dog: 2. ‘’’Try to model a real dog ‘’’ 3. def __init__(self, name, age): 4. self.name = name 5. self.age = age 6. self.owner = “Not Set Yet ” 7. def sit(self): 8. print(self.name.title() + “ is now sitting “) 9. def roll(self): 10. print(self.name.title() + “ is now rolling “) 11. def set_owner_name(self, name): 12. self.owner = name Class Constructor - initialize attributes Class Name method
Creating an Object ▸ Creating an Object from a Class: ▸ To access methods and attributes: ▸ To set value outside/inside class definition: object_name = ClassName(argument_1,argument_2,…) object_name.attribute_name object_name.method_name() arguments will pass to constructor object_name.attribute_name = value self.attributes_name = value the value can be int/float/str/bool or another object dot operator connect object with attributes and methods
Example of Creating an Object ▸ The term object and instance of a class are the same thing. Here we create object my_dog from Dog Class and call method sit() using dot operator 1. my_dog = Dog(“Diffenbaker”, 6) 2. print(“My dog name is: ” + my_dog.name ) 3. my_dog.sit()
Modifying Attribute’s Value ▸ Directly: ▸ Through a Method: 1. my_dog = Dog(“Diffenbaker”, 6) 2. my_dog.owner = “Sina” 1. my_dog = Dog(“Diffenbaker”, 6) 2. my_dog.set_owner_name(“Sina”)
self must be always pass to a method Class Constructor Constructor arguments data attributes
no arguments no parameters self is default
direct access access through a method
WHAT!!! WE CAN ACCESS T O A N AT T R I B U T E DIRECTLY?! WHAT HAPPEN TO ENCAPSULATION?! Attribute mustn’t be private any more?
YOU CAN MAKE A VARIABLE PRIVATE BY USING 2 UNDERSCORE BEFORE IT’S NAME AND USING 1 UNDERSCORE TO MAKE IT PROTECTED protected is not really protected. It’s just a hint for a responsible programmer
PYTHON DATA PIRACY MODEL IS NOT WHAT YOU USED TO IN C++/JAVA
we can not directly access a private attribute attributes are private It’s not a syntax error but it’s better not to use () after Class Name
Access through method
TRY TO EXPLAIN WHAT HAPPEN IN THE NEXT SLIDE CODE?
????
CREATING A LIST OF OBJECTS we can use objects in other data structures
USING OBJECTS AS A METHOD ARGUMENT AND RETURN VALUE
list of objectscall print_students_list()
IN PYTHON EVERYTHING IS AN OBJECTnumbers/str/bool/list/dictionary/…/ function and even class is an object.
Object Identity ▸ The id() built-in function is used to find the identity of the location of the object in memory. ▸ The return value is a unique and constant integer for each object during its lifetime: 1. my_dog = Dog(“Diffenbaker”, 6) 2. print(id(my_dog) )
Identifying Object’s Class ▸ The isinstance() built-in method is check whether an object is an instance of a given class or not. isinstance(object_name,ClassName) True/False
Class Attributes vs. Data Attributes ▸ Data Attributes are instance variables that are unique to each object of a class, and Class attributes are class variables that is shared by all objects of a class. Class Attributes are static and they are exist without instantiating an Object
Inheritance ▸ Inheritance enables new classes to receive or inherit attributes and methods of existing classes. ▸ To build a new class, which is already similar to one that already exists, then instead of creating a new class from scratch you can reference the existing class and indicate what is different by overriding some of its behavior or by adding some new functionality. ▸ Inheritance also includes __init__() method. ▸ if you do not define it in a derived class, you will get the one from the base class. we can also add new attributes.
SuperClass SubClass & SuperClass SubClass More Abstract Less Abstract Also Called Hypernymy Also Called Hyponymy SubClass
Inheritance Syntax class DriveClass(BaseClass): def __init__(self, drive_class_parameters,base_class_parameters) super().__init__(base_class_parameters) self.drive_class_instance_variable = drive_class_parameters
SuperClass to call super class constructor and passed name and age SuperClass
WHY OBJECT-ORIENTED AND NOT CLASS-ORIENTED?
“ The Way You Do One Thing Is the Way You Do Everything”

Python Programming - Object-Oriented

  • 1.
    CS.QIAU - Winter2020 PYTHONObject-Oriented - Session 8 Omid AmirGhiasvand Programming
  • 2.
    PROGRAMMING IS A TYPEOF IMPERATIVE PROGRAMMING PARADIGM OBJECT-ORIENTED Objects are the building blocks of an application
  • 3.
    IMPERATIVE PROGRAMMING IS A PROGRAMMINGPARADIGM THAT USES STATEMENTS THAT CHANGE A PROGRAM’S STATE.
  • 4.
    DECLARATIVE PROGRAMMING IS A PROGRAMMINGPARADIGM THAT EXPRESSES THE LOGIC OF A COMPUTATION WITHOUT DESCRIBING ITS CONTROL FLOW.
  • 5.
  • 6.
    Object-Oriented Programming ▸ Thebasic idea of OOP is that we use Class & Object to model real-world things that we want to represent inside our programs. ▸ Classes provide a means of bundling “data” and “behavior” together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Programming or Software Engineering
  • 7.
    OBJECT an object representsan individual thing and its method define how it interacts with other things A CUSTOM DATA TYPE CONTAINING BOTH ATTRIBUTES AND METHODS
  • 8.
    CLASS objects are instanceof classes IS A BLUEPRINT FOR THE OBJECT AND DEFINE WHAT ATTRIBUTES AND METHODS THE OBJECT WILL CONTAIN
  • 9.
    OBJECTS ARE LIKEPEOPLE. THEY ARE LIVING, BREATHING THINGS THAT HAVE KNOWLEDGE INSIDE THEM ABOUT HOW TO DO THINGS AND HAVE MEMORY INSIDE THEM SO THEY CAN REMEMBER THINGS. AND RATHER THAN INTERACTING WITH THEM AT A VERY LOW LEVEL, YOU INTERACT WITH THEM AT A VERY HIGH LEVEL OF ABSTRACTION, LIKE WE’RE DOING RIGHT HERE. HERE’S AN EXAMPLE: IF I’M YOUR LAUNDRY OBJECT, YOU CAN GIVE ME YOUR DIRTY CLOTHES AND SEND ME A MESSAGE THAT SAYS, “CAN YOU GET MY CLOTHES LAUNDERED, PLEASE.” I HAPPEN TO KNOW WHERE THE BEST LAUNDRY PLACE IN SAN FRANCISCO IS. AND I SPEAK ENGLISH, AND I HAVE DOLLARS IN MY POCKETS. SO, I GO OUT AND HAIL A TAXICAB AND TELL THE DRIVER TO TAKE ME TO THIS PLACE IN SAN FRANCISCO. I GO GET YOUR CLOTHES LAUNDERED, I JUMP BACK IN THE CAB, I GET BACK HERE. I GIVE YOU YOUR CLEAN CLOTHES AND SAY, “HERE ARE YOUR CLEAN CLOTHES.” YOU HAVE NO IDEA HOW I DID THAT. YOU HAVE NO KNOWLEDGE OF THE LAUNDRY PLACE. MAYBE YOU SPEAK FRENCH, AND YOU CANNOT EVEN HAIL A TAXI. YOU CANNOT PAY FOR ONE, YOU DO NOT HAVE DOLLARS IN YOUR POCKET. YET I KNEW HOW TO DO ALL OF THAT. AND YOU DIDN’T HAVE TO KNOW ANY OF IT. ALL THAT COMPLEXITY WAS HIDDEN INSIDE OF ME, AND WE WERE ABLE TO INTERACT AT A VERY HIGH LEVEL OF ABSTRACTION. THAT’S WHAT OBJECTS ARE.THEY ENCAPSULATE COMPLEXITY, AND THE INTERFACES TO THAT COMPLEXITY ARE HIGH LEVEL. Do you know who give this description?
  • 10.
    Object-Oriented Benefits ▸ Muchmore easier to maintain. ▸ Code Reuse. ▸ Cleaner Code. ▸ Better Architecture. ▸ Abstraction. ▸ Fewer Faults. Why? Fault Error Failure Fault-Tolerance Error MaskingHere we are Programming or Software Engineering
  • 11.
    Definition of theClass ▸ A Class is a Template or Blueprint which is used to instantiate objects. Include: ▸ Data/Attributes/Instance variable ▸ Behavior/Methods ▸ An Object refer to particular instance of a class where the object contains instance variables (attributes) and methods defined in the class. attributes Methods The act of creating object from class is called instantiation
  • 12.
    O B JE C T ’ S AT T R I B U T E S REPRESENT THE STATE OF THE THING WE TRY TO MODEL. data == attributes == instance variables != class variables
  • 13.
  • 14.
    Encapsulation Concept ▸ Encapsulationis the process of combining attributes and methods that work on those attributes into a single unit called class. ▸ Attributes are not accessed directly; it is accessed through the methods present in the class. ▸ Encapsulation ensures that the object’s internal representation (its state and behavior) are hidden from the rest of the application attributes Methods Information and implementation hiding
  • 15.
  • 16.
    Creating a Class ▸Classes are defined by using class keyword, followed by ClassName and a colon. ▸ Class definition must be executed before instantiating an object from it. class ClassName : def __init__(self,parameter_1,parameter_2,…): self.attribute_1 = parameter_1 … def method_name(self,parameter_1, …): statement-1 class constructor - initializing object
  • 17.
    Example of Creatinga Class ▸ Creating a Class for Dog - Any dog 1. class Dog: 2. ‘’’Try to model a real dog ‘’’ 3. def __init__(self, name, age): 4. self.name = name 5. self.age = age 6. self.owner = “Not Set Yet ” 7. def sit(self): 8. print(self.name.title() + “ is now sitting “) 9. def roll(self): 10. print(self.name.title() + “ is now rolling “) 11. def set_owner_name(self, name): 12. self.owner = name Class Constructor - initialize attributes Class Name method
  • 18.
    Creating an Object ▸Creating an Object from a Class: ▸ To access methods and attributes: ▸ To set value outside/inside class definition: object_name = ClassName(argument_1,argument_2,…) object_name.attribute_name object_name.method_name() arguments will pass to constructor object_name.attribute_name = value self.attributes_name = value the value can be int/float/str/bool or another object dot operator connect object with attributes and methods
  • 19.
    Example of Creatingan Object ▸ The term object and instance of a class are the same thing. Here we create object my_dog from Dog Class and call method sit() using dot operator 1. my_dog = Dog(“Diffenbaker”, 6) 2. print(“My dog name is: ” + my_dog.name ) 3. my_dog.sit()
  • 20.
    Modifying Attribute’s Value ▸Directly: ▸ Through a Method: 1. my_dog = Dog(“Diffenbaker”, 6) 2. my_dog.owner = “Sina” 1. my_dog = Dog(“Diffenbaker”, 6) 2. my_dog.set_owner_name(“Sina”)
  • 21.
    self must be alwayspass to a method Class Constructor Constructor arguments data attributes
  • 22.
  • 24.
  • 25.
    WHAT!!! WE CANACCESS T O A N AT T R I B U T E DIRECTLY?! WHAT HAPPEN TO ENCAPSULATION?! Attribute mustn’t be private any more?
  • 26.
    YOU CAN MAKEA VARIABLE PRIVATE BY USING 2 UNDERSCORE BEFORE IT’S NAME AND USING 1 UNDERSCORE TO MAKE IT PROTECTED protected is not really protected. It’s just a hint for a responsible programmer
  • 27.
    PYTHON DATA PIRACYMODEL IS NOT WHAT YOU USED TO IN C++/JAVA
  • 28.
    we can not directlyaccess a private attribute attributes are private It’s not a syntax error but it’s better not to use () after Class Name
  • 29.
  • 30.
    TRY TO EXPLAINWHAT HAPPEN IN THE NEXT SLIDE CODE?
  • 31.
  • 32.
    CREATING A LISTOF OBJECTS we can use objects in other data structures
  • 35.
    USING OBJECTS ASA METHOD ARGUMENT AND RETURN VALUE
  • 36.
  • 37.
    IN PYTHON EVERYTHING ISAN OBJECTnumbers/str/bool/list/dictionary/…/ function and even class is an object.
  • 38.
    Object Identity ▸ Theid() built-in function is used to find the identity of the location of the object in memory. ▸ The return value is a unique and constant integer for each object during its lifetime: 1. my_dog = Dog(“Diffenbaker”, 6) 2. print(id(my_dog) )
  • 39.
    Identifying Object’s Class ▸The isinstance() built-in method is check whether an object is an instance of a given class or not. isinstance(object_name,ClassName) True/False
  • 41.
    Class Attributes vs.Data Attributes ▸ Data Attributes are instance variables that are unique to each object of a class, and Class attributes are class variables that is shared by all objects of a class. Class Attributes are static and they are exist without instantiating an Object
  • 43.
    Inheritance ▸ Inheritance enablesnew classes to receive or inherit attributes and methods of existing classes. ▸ To build a new class, which is already similar to one that already exists, then instead of creating a new class from scratch you can reference the existing class and indicate what is different by overriding some of its behavior or by adding some new functionality. ▸ Inheritance also includes __init__() method. ▸ if you do not define it in a derived class, you will get the one from the base class. we can also add new attributes.
  • 44.
    SuperClass SubClass & SuperClass SubClass More Abstract LessAbstract Also Called Hypernymy Also Called Hyponymy SubClass
  • 45.
    Inheritance Syntax class DriveClass(BaseClass): def__init__(self, drive_class_parameters,base_class_parameters) super().__init__(base_class_parameters) self.drive_class_instance_variable = drive_class_parameters
  • 46.
    SuperClass to call super classconstructor and passed name and age SuperClass
  • 48.
    WHY OBJECT-ORIENTED ANDNOT CLASS-ORIENTED?
  • 49.
    “ The WayYou Do One Thing Is the Way You Do Everything”