object oriented programming
play

Object-Oriented Programming Scientific Programming with Python - PowerPoint PPT Presentation

Department of Physics Object-Oriented Programming Scientific Programming with Python Andreas Weiden Based on talks by Niko Wilbert and Roman Gredig This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 License . 24/06/2019


  1. Department of Physics Object-Oriented Programming Scientific Programming with Python Andreas Weiden Based on talks by Niko Wilbert and Roman Gredig This work is licensed under the Creative Commons Attribution-ShareAlike 3.0 License . 24/06/2019 Page 1

  2. Department of Physics Outline What is OOP? Fundamental Principles of OOP Specialities in Python Science Examples Design Patterns 24/06/2019 Page 2

  3. Department of Physics Setting the scene Object-oriented programming is a programming paradigm . ◮ Imperative programming ◮ Object-oriented ◮ Procedural ◮ Declarative programming ◮ Functional ◮ Logic 24/06/2019 Page 3

  4. Department of Physics What is Object-Oriented Programming? Aim to segment the program into instances of different classes of objects: ◮ Instance variables to describe the state of the object ◮ Methods to model the behaviour of the object The definition of a class can be considered like a blue print . The program will create instances of classes and execute methods of these instances. 24/06/2019 Page 4

  5. Department of Physics Why might OOP be a good idea? DRY (Don’t repeat yourself): KIS (Keep it simple): OOP means to create the functionality of The OOP paradigm allows to split the classes once with the possibility to use functionality of programs into the basic them repeatedly in different programms. building blocks and the algorithm In addition inheritance in OOP allows us to invoking them. Thus it creates a natural easily create new classes by extending structure within your code. existing classes (see below). At one point the problem to solve becomes so complicated that a single sequence of program instructions is not sufficient to effectively maintain the code. 24/06/2019 Page 5

  6. Department of Physics Example of a class ◮ Started with class keyword. class Dog: def __init__(self , color="brown"): ◮ Methods defined as functions in class self.color = color scope with at least one argument def make_sound (self ): (usually called self ). print("Wuff!") ◮ Special method __init__ called when # create an instance ’snoopy ’ of the class Dog a new instance is created. snoopy = Dog () ◮ Always define your data attributes first # first argument (self) is bound in __init__ . # to this Dog instance snoopy.make_sound () # change snowy ’s color snoopy.color = "yellow" 24/06/2019 Page 6

  7. Department of Physics Fundamental Principles of OOP (I) Encapsulation In Python: ◮ Only what is necessary is exposed ◮ No explicit declaration of (public interface) to the outside. variables/functions as private or public. ◮ Usually parts supposed to be private ◮ Implementation details are hidden to provide abstraction. Abstraction should start with an underscore _ . not leak implementation details. ◮ Python works with documentation and ◮ Abstraction allows to break up a large conventions instead of enforcement. problem into understandable parts. 24/06/2019 Page 7

  8. Department of Physics Example of Encapsulation class Dog: def __init__(self , color="brown"): ◮ The author of the class Dog self.color = color self._mood = 5 wants you to pat and beat the dog to change its mood. def _change_mood (self , change ): self._mood += change ◮ Do not use the _mood variable self. make_sound () or the _change_mood method def make_sound (self ): directly. if self._mood < 0: print("Grrrr!") else: print("Wuff!") def pat(self ): self. _change_mood (1) def beat(self ): self. _change_mood (-2) 24/06/2019 Page 8

  9. Department of Physics Fundamental Principles of OOP (II) Inheritance In Python: ◮ Define new classes as subclasses that ◮ Inherit from one or multiple classes are derived from / inherit / extend a (latter one not recommended!) parent class . ◮ Invocation of parent methods with ◮ Override parts with specialized super function. behavior and extend it with additional ◮ All classes are derived from object , functionality. even if this is not specified explicitly. 24/06/2019 Page 9

  10. Department of Physics Example of Inheritance class Mammal: from mammal import Mammal def __init__(self , color="grey"): self.color = color class Dog(Mammal ): self._mood = 5 def __init__(self , color="brown"): super (). __init__(color) def _change_mood (self , change ): self._mood += change def make_sound (self ): self. make_sound () if self._mood < 0: print("Grrrr!") def make_sound (self ): else: raise NotImplementedError print("Wuff!") ◮ super().__init__(color) is the call def pat(self ): self. _change_mood (1) to the parent constructor. ◮ super allows also to explicitly access def beat(self ): self. _change_mood (-2) methods of the parent class. ◮ This is usually done when extending a method of the parent class. 24/06/2019 Page 10

  11. Department of Physics Fundamental Principles of OOP (III) Polymorphism In Python: ◮ Different subclasses can be treated ◮ Python is a dynamically typed like the parent class , but execute their language , which means that the type specialized behavior. (class) of a variable is only known when the code runs. ◮ Example: When we let a mammal ◮ Duck Typing: No need to know the make a sound that is an instance of the dog class, then we get a barking sound. class of an object if it provides the required methods: “When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.” ◮ Type checking can be performed via the isinstance function, but generally prefer duck typing and polymorphism. 24/06/2019 Page 11

  12. Department of Physics Example of Polymorphism ◮ caress would work for all from animals import Dog , Cat , Bear objects having a method pat , def caress(mammal , number_of_pats ): not just mammals. if isinstance (mammal , Bear ): raise TypeError("Bad Idea!") ◮ isinstance(mammal, Bear) for _ in range( number_of_pats ): checks if mammal is a bear. mammal.pat () ◮ Dynamic typing makes proper d, c, b = Dog(), Cat(), Bear () function overloading caress(d, 3) # "Wuff !" (3x) caress(c, 3) # "Purr !" (3x) impossible! caress(b, 3) # raises TypeError 24/06/2019 Page 12

  13. Department of Physics Python Specialities – Magic Methods ◮ Magic methods (full list here) class Dog: def __init__(self , color="brown"): start and end with two self.color = color underscores (“dunder”). self._mood = 5 ◮ They customise standard def __repr__(self ): Python behavior ( e.g. string return f"This is a {self.color} dog" representation or operator snowy = Dog("white") definition). print(snowy) # This is a white dog 24/06/2019 Page 13

  14. Department of Physics Python Specialities – Property class Dog: def __init__(self , color="brown"): ◮ property has upto four arguments: self.color = color self._mood = 5 1. Getter 2. Setter def _get_mood(self ): 3. Deleter if self._mood < 0: 4. Documentation string return "angry" return "happy" ◮ Access calculated values as if they were stored data attributes. def _set_mood(self , value ): if not -10 <= value <= 10: ◮ Define read-only “data attributes”. raise ValueError ("Bad range!") self._mood = value ◮ Check if value assigned to “data attribute” fullfills conditions. mood = property(_get_mood , _set_mood) ◮ Can also be used as a Python snowy = Dog("white") decorator. print("Snowy is", snowy.mood) # Snowy is happy snowy.mood = -3 print("Snowy is", snowy.mood) # Snowy is angry 24/06/2019 Page 14

  15. Department of Physics Python Specialities – Property class Dog: def __init__(self , color="brown"): ◮ property has upto four arguments: self.color = color self._mood = 5 1. Getter 2. Setter @property 3. Deleter def mood(self ): 4. Documentation string if self._mood < 0: return "angry" ◮ Access calculated values as if they return "happy" were stored data attributes. @mood.setter ◮ Define read-only “data attributes”. def mood(self , value ): if not -10 <= value <= 10: ◮ Check if value assigned to “data raise ValueError ("Bad range!") attribute” fulfils conditions. self._mood = value ◮ Can also be used as a Python # create an instance ’snowy ’ of the class Dog decorator. snowy = Dog("white") print("Snowy is", snowy.mood) snowy.mood = 100 24/06/2019 Page 15

  16. Department of Physics Python Specialities – Classmethods ◮ A classmethod takes as its first class Dog: def __init__(self , name , color="brown"): argument a class instead of an instance self.name = name of the class. It is therefore called cls self.color = color instead of self . self._mood = 5 ◮ The method should return an object of @classmethod def from_string (cls , s): the class. name , *color = s.split(",") ◮ This allows you to write multiple if color: constructors for a class, e.g.: return cls(name , color) ◮ The default __init__ constructor. return cls(name) ◮ One constructor from a serialized snowy = Dog. from_string ("snowy ,white") string. ◮ One that reads it from a database or file. ◮ . . . 24/06/2019 Page 16

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend