1 / 80

Guide to Programming with Python Book is by Michael Dawson https://amazon/dp/1423901126/

Learn object-oriented programming with Python using classes, constructors, attributes, and methods. Understand fundamental OOP concepts like information hiding, abstraction, encapsulation, and more. Create and instantiate objects easily.

johntsmith
Download Presentation

Guide to Programming with Python Book is by Michael Dawson https://amazon/dp/1423901126/

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Guide to Programming with PythonBook is by Michael Dawson https://www.amazon.com/dp/1423901126/ Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods

  2. Objectives • Create classes to define objects • Write methods and create attributes for objects • Instantiate objects from classes • Restrict access to an object’s attributes • Work with both new-style and old-style classes • The Critter Caretaker Program Guide to Programming with Python

  3. Python Is Object-Oriented • Object-oriented programming (OOP): Methodology that defines problems in terms of objects that send messages to each other • dir(1) • In a game, a Missile object could send a Ship object a message to Explode • OOP not required, unlike Java and C# Guide to Programming with Python

  4. Understanding Object-Oriented Basics • OOP allows representation of real-life objects as software objects (e.g., a dictionary as an object) • Object: A single software unit that combines attributes and methods • Attribute: A "characteristic" of an object; like a variable associated with a kind of object • Method: A "behavior" of an object; like a function associated with a kind of object • Class: Code that defines the attributes and methods of a kind of object (A class is a collection of variables and functions working with these variables)

  5. Fundamental Concepts of OOP • Information hiding • Abstraction • Encapsulation • Modularity • Polymorphism • Inheritance Guide to Programming with Python

  6. Creating Classes for Objects class Puppy(object): def __init__(self, name, color): self.name = name self.color = color def bark(self): print "I am", color, name puppy1 = Puppy("Max", "brown") puppy1.bark() puppy2 = Puppy("Ruby", "black") puppy2.bark() • Class: Code that defines the attributes and methods of a kind of object • Instantiate: To create an object; A single object is called an Instance

  7. The Simple Critter Program class Critter(object): """A virtual pet""" def talk(self): print "Hi. I'm an instance of class Critter.” # main crit = Critter() crit.talk() • Define class: • Class name, begin with capital letter, by convention • object: class based on (Python built-in type) • Define a method • Like defining a function • Must have a special first parameter, self, which provides way for a method to refer to object itself

  8. Class methods & “self” parameter • Class methods have only one specific difference from ordinary functions--they must have an extra first name that has to be added to the beginning of the parameter list • You do not give a value for this parameter(self) when you call the method, Python will provide it. • This particular variable refers to the object itself, and by convention, it is given the name self. Guide to Programming with Python

  9. Instantiating an Object crit = Critter() • Create new object with class name followed by set of parentheses • Critter() creates new object of class Critter • Can assign a newly instantiated object to a variable of any name • crit = Critter() assigns new Critter object tocrit • Avoid using variable that's same name as the class name in lowercase letters Guide to Programming with Python

  10. Creating Multiple Objects crit1 = Critter() crit2 = Critter() • Creating multiple objects is easy • Two objects created here • Each object is independent, full-fledged critter Guide to Programming with Python

  11. Invoking a Method crit.talk() • Any Critter object has method talk() • crit.talk() invokes talk() method of Critter object crit • Prints string "Hi. I'm an instance of class Critter." simple_critter.py Guide to Programming with Python

  12. Using Constructors • Constructor: A special method that is automatically invoked right after a new object is created • Usually write one in each class • Usually sets up the initial attribute values of new object in constructor Guide to Programming with Python

  13. Creating a Constructor def __init__(self): print "A new critter has been born!" • New Critter object automatically announces itself to world • __init__ • Is special method name • Automatically called by new Critter object Guide to Programming with Python

  14. Initializing Attributes class Critter(object): def __init__(self, name): self.name = name ... crit1 = Critter("Poochie”) • Can have object’s attributes automatically created and initialized through constructor (Big convenience!) • self – first parameter in every instance method • selfreceives reference to new Critterobject • namereceives"Poochie" • self.name = namecreates the attribute namefor object and sets to "Poochie" • crit1gets new Critterobject

  15. Accessing Attributes class Critter(object): ... def talk(self): print "Hi. I'm", self.name, "\n" ... crit1.talk() print crit1.name • Assessing attributes using methods: talk() • Uses aCritterobject’snameattribute • Receives reference to the object itself into self • Accessing Attributes Directly Guide to Programming with Python

  16. Printing an Object (How?) class Critter(object): ... def __str__(self): rep = "Critter object\n" rep += "name: " + self.name + "\n" return rep ... print crit1 • __str__ is a special method that returns string representation of object (sample code) Guide to Programming with Python

  17. Two More Special Methods class Puppy(object): def __init__(self): self.name = [] self.color = [] def __setitem__(self, name, color): self.name.append(name) self.color.append(color) def __getitem__(self, name): if name in self.name: return self.color[self.name.index(name)] else: return None dog = Puppy() dog['Max'] = 'brown' dog['Ruby'] = 'yellow’ print "Max is", dog['Max']

  18. Using Class Attributes and Static Methods • Class attribute: A single attribute that’s associated with a class itself (not an instance!) • Static method: A method that’s associated with a class itself • Class attribute could be used for counting the total number of objects instantiated, for example • Static methods often work with class attributes Guide to Programming with Python

  19. Creating a Class Attribute class Critter(object): total = 0 • total = 0creates class attribute totalset to 0 • Assignment statement in class but outside method creates class attribute • Assignment statement executed only once, when Python first sees class definition • Class attribute exists even before single object created • Can use class attribute without any objects of class in existence Guide to Programming with Python

  20. Accessing a Class Attribute class Critter(object): total = 0 def status(): print "Total critters", Critter.total status = staticmethod(status) def __init__(self, name): Critter.total += 1 print Critter.total #the class print crit1.total #the instance #crit1.total += 1 # won’t work; can't assign new value to a class attribute through instance

  21. Creating a Static Method class Critter(object): ... def status(): print "Total critters", Critter.total status = staticmethod(status) • status() • Is static method • Doesn't have self in parameter list because method will be invoked through class not object • staticmethod() • Built-in Python function • Takes method and returns static method

  22. Invoking a Static Method ... crit1 = Critter("critter 1") crit2 = Critter("critter 2") crit3 = Critter("critter 3") Critter.status() • Critter.status() • Invokes static method status()defined inCritter • Prints a message stating that 3 critters exist • Works because constructor increments class attribute total, which status()displays Guide to Programming with Python

  23. Setting default values class Person(object): def __init__(self, name="Tom", age=20): self.name = name self.age = age def talk(self): print "Hi, I am", self.name def __str__(self): return "Hi, I am " + self.name one = Person(name="Yuzhen", age = "forever 20") print one two = Person() print two Guide to Programming with Python

  24. Summary • Object-oriented Programming (OOP) is a methodology of programming where new types of objects are defined • An object is a single software unit that combines attributes and methods • An attribute is a “characteristic” of an object; it’s a variable associated with an object (“instance variable”) • A method is a “behavior” of an object; it’s a function associated with an object • A class defines the attributes and methods of a kind of object Guide to Programming with Python

  25. Summary (continued) • Each instance method must have a special first parameter, called self by convention, which provides a way for a method to refer to object itself • A constructor is a special method that is automatically invoked right after a new object is created • A class attribute is a single attribute that’s associated with a class itself • A static method is a method that’s associated with a class itself Guide to Programming with Python

  26. Guide to Programming with Python Chapter Eight (Part II) Object encapsulation, privacy, properties; Critter Caretaker game

  27. More on OOP • Object-oriented programming (OOP) is a programming language model organized around "objects" rather than "actions”, and data rather than logic (from searchSOA.com) • An object is a software bundle of related attributes and behavior (methods) • A class is a blueprint or prototype from which objects are created • Each object is capable of receiving messages, processing data, and sending messages to other objects (or client codes) and can be viewed as an independent module with a distinct role or functionality

  28. Who Are You class Person(object): total = 0 #class attribute def __init__(self, name="Tom", age=20, location="Bloomington"): self.name = name self.age = age self.location = location Person.total += 1 def talk(self): print "Hi, I am", self.name, "and I am", self.age, "years old" def __str__(self): return "Hi, I am " + self.name + " and I am " + str(self.age) + " years old" print "Before creating instances: Person.total=", Person.total aperson = Person() print "Hi, I am", aperson.name, "and I am", aperson.age, "years old” aperson.talk() print aperson ruby = Person("Ruby", 21) print "Hi, I am", ruby.name, "and I am", ruby.age, "years old” ruby.talk() print ruby print "Now Person.total=", Person.total

  29. Understanding Object Encapsulation • Client code should • Communicate with objects through method parameters and return values • Avoid directly altering value of an object’s attribute • Objects should • Update their own attributes • Keep themselves safe by providing indirect access to attributes through methods Guide to Programming with Python

  30. Private vs Public Attributes and Methods • Public: Can be directly accessed by client code • Private: Cannot be directly accessed (easily) by client code • Public attribute or method can be accessed by client code • Private attribute or method cannot be (easily) accessed by client code • By default, all attributes and methods are public • But, can define an attribute or method as private Guide to Programming with Python

  31. Creating Private Attributes class Critter(object): def __init__(self, name, mood): self.name = name # public attribute self.__mood = mood # private attribute • name • Created as any attribute before • Public attribute (default) • __mood • Private attribute • Two underscore characters make private attribute • Begin any attribute with two underscores to make private Guide to Programming with Python

  32. Accessing Private Attributes class Critter(object): ... def talk(self): print "\nI'm", self.name print "Right now I feel", self.__mood, "\n" • Private attributes • Can be accessed inside the class • Can’t be accessed directly through object • crit1.__moodwon’t work • Technically possible to access through object, but shouldn’t crit1._Critter__mood #instance._classname__variable • Pseudo-encapsulation cannot really protect data from hostile code Guide to Programming with Python

  33. Creating Private Methods class Critter(object): ... def __private_method(self): print "This is a private method." • Like private attributes, private methods defined by two leading underscores in name • __private_method() is a private method Guide to Programming with Python

  34. Accessing Private Methods class Critter(object): ... def public_method(self): print "This is a public method." self.__private_method() • Like private attributes, private methods • Can be accessed inside class • Can’t be accessed directly through object • crit1.__private_method() won’t work • Technically possible to access through object, but shouldn’t crit1._Critter__private_method()works Guide to Programming with Python

  35. Controlling Attribute Access • Instead of denying access to an attribute, can limit access to it • Example: client code can read, but not change attribute • Properties can manage how attribute is accessed or changed Guide to Programming with Python

  36. Using Get Methods class Critter(object): ... def get_name(self): return self.__name ... crit = Critter("Poochie") print crit.get_name() • Get method: A method that gets the value of an attribute, which is often private; by convention, name starts with “get” • get_name() provides indirect access to __name Guide to Programming with Python

  37. Using Set Methods class Critter(object): ... def set_name(self, new_name): if new_name == "": print "Critter's name can't be empty string." else: self.__name = new_name print "Name change successful. ” crit = Critter("Poochie") crit.set_name("Randolph") • Set method: Sets an attribute, often private, to a value; by convention, name starts with "set”, e.g., set_name()

  38. Using Properties (Optional) class Critter(object): ... name = property(get_name, set_name) • Property: An interface that allows indirect access to an attribute by wrapping access methods around dot notation • property()function • Takes accessor methods and returns a property • Supply with get and set methods for controlled access to private attribute • Supply only get method for “read-only” property Guide to Programming with Python

  39. Using Properties (Optional) >>> print crit.name Randolph >>> crit.name = "Sammy" Name change successful. >>> print crit.name Sammy >>> crit.name = "" Critter's name can't be empty string. Guide to Programming with Python

  40. Respect Privacy • Classes • Write methods (e.g., get & set methods) so no need to directly access object’s attributes • Use privacy only for attributes and methods that are completely internal to operation of object • Objects • Minimize direct reading of object’s attributes • Avoid directly altering object’s attributes • Never directly access object’s private attributes or methods Guide to Programming with Python

  41. New-Style and Old-Style Classes class Critter(object): # new-style class class Critter: # old-style class • New-style class: A class that is directly or indirectly based on the built-in object • Old-style class: A class that is not based on object, directly or indirectly • New-style classes • Introduced in Python 2.2 • Significant improvements over old-style • Create instead of old-style classes whenever possible Guide to Programming with Python

  42. Summary • Public attributes and methods can be directly accessed by client code • Private attributes and methods cannot (easily) be directly accessed by client code • A get method gets the value of an attribute; by convention, its name starts with “get” • A set method sets an attribute to a value; by convention, its name starts with “set” Guide to Programming with Python

  43. Guide to Programming with Python Chapter Nine Inheritance Working with multiple objects

  44. OOP So Far • Object-oriented programming is a programming language model organized around "objects” • An object is a software bundle of related attributes and behavior (methods) • A class is a blueprint or prototype from which objects are created class Player(object): def __init__(self, name = "Enterprise", fuel = 0): self.name = name self.fuel = fuel def status(self): ... myship = Ship("Appolo") myship.status() • Object encapsulation & respect privacy

  45. Objectives • Inheritance makes objects (classes) special • Derive new classes from existing ones • Extend the definition of existing classes • Override method definitions of existing classes • Create objects of different classes in the same program • Allow objects to communicate with each other • Create more complex objects by combining simpler ones • The Blackjack Game Guide to Programming with Python

  46. Inheritance Models “is a” Relationship Car Sports car Convertible Van Animals Mammals Fish Reptile Dog Cat Human Guide to Programming with Python

  47. Using Inheritance to Create New Classes • Inheritance: An element of OOP that allows a new class to be based on an existing one where the new automatically gets (or inherits) all of the methods and attributes of the existing class • The children classes get all the capabilities (methods) and properties (attributes) the parent class has; the children classes are also called derived classes • Get the code for free! (code-reuse) – inheritance allows a new class to re-use code which already existed in another class (the parent class) Guide to Programming with Python

  48. Derived Classes are New Classes • To create specializations of existing classes or objects by adding new attributes and methods! • often called subtyping when applied to classes. In specialization, the new class or object has data or behavior aspects that are not part of the inherited class. • Over-ridding (e.g., over-ridding of the + operator, so + has different meaning, addition of two numbers, concatenation of two strings, etc) – the same method that does something different Guide to Programming with Python

  49. Inheritance Example: Animal Class class Animal(object): def __init__(self, name): # Constructor self.name = name def get_name(self): return self.name class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' animals = [Cat('Missy'), Cat('Mr. Bojangles'), Dog('Lassie')] for animal in animals: print animal.talk() + ' I am ' + animal.get_name() Base class: A class upon which another is based; it is inherited from by a derived class Derived class: A class that is based upon another class; it inherits from a base class

  50. Altering the Behavior of Inherited Methods: Overriding • Override: To redefine how inherited method of base class works in derived class • Two choices when overriding • Completely new functionality vs. overridden method • Incorporate functionality of overridden method, add more Guide to Programming with Python

More Related