week6.pdf
Document Details
Uploaded by WarmHouston360
Tags
Full Transcript
Introduction to OOP Gilad Gressel Amrita School of Engineering Introduction What is an object in python What is OOP Class instances (objects) you have already been using Place your Webcam Video here Clas...
Introduction to OOP Gilad Gressel Amrita School of Engineering Introduction What is an object in python What is OOP Class instances (objects) you have already been using Place your Webcam Video here Classes are blueprints Size 100% Classes allow you to create your own object types 1 What is an object in python? In python, everything you can assign to a variable is an object 5, ‘hello’, [1,2,3,4], (‘hi,’bye’), {‘hi’:a}, are all objects print is an object! (you can assign it to a variable) The only things that are not objects are the reserved keywords like in, for, if, else, etc So actually we have been doing object oriented programming this whole time But… what is object oriented programming? 2 Object Oriented Programming … can be defined a few ways Some would say it requires that your language support this: objects and classes inheritance polymorphism encapsulation composition Python does have those things (encapsulation / composition very weakly) However, the main “thing” OOP languages have is classes 3 What classes have we been using? You have been using classes this whole time – anything that is an object (which is everything) was created from a class Classes define the type of a variable, they are the “rules” of the object. Classes are blueprints for objects. When run a = [1,2,3]it is creating an instance of the class List which dictates that is has methods (clear, append, extend, etc) an index w/ slicing rules about what operators like + or * will do. Every list that you create is an instance of the Class List 4 Classes are blueprints: Objects are instances A class is a blueprint When you build a house, you get blueprints (or you make them) Then the construction crew comes and builds from the plan The resulting house is not the blueprint, it’s the physical realization of the plan Objects are instances – or physical realizations of the blueprint which is the Class 5 Blueprints don’t always generate identical objects A blueprint can be used many times to build many different homes, but the colors of the home do not need to be the same Importantly not all instances of an object are the same a = [1,2,3,4] b = [2,3,4,5] a!=b Notably, the methods (append, clear, etc) are identical for all lists but the contents of the list can be different 6 Why use classes? The benefit of a class is that you can define your own object type It is another level of abstraction! This abstraction allows you to create your own object types The ability to create classes allows programmers to create vast applications such as: numpy requests csprng 7 Coding a game You can have code that says: player_name = ‘bob’ player_lives = 5 player_inventory= [‘book’, ‘map’, ‘compass’] player_current_location = ‘sector2’ You also need code that allows the player to: move examine objects pick up objects use objects With object oriented program, you can program a class, which represents all the information and methods of the player This is simply another level of abstraction that makes programming complex ideas more achievable 8 Conclusion Classes are powerful abstractions that are the center of Object Oriented Programming Classes are blueprints which organize both Place your Webcam Video here information (attributes) Size 100% and functions (methods) into a single data type 9 Classes - Syntax Gilad Gressel Amrita School of Engineering Introduction The barest class Class methods Class attributes A typical example Place your Webcam Video here Size 100% 1 Define a class The barest possible class is defined with the follow syntax You create an instance by calling the class There are two common statements used: attributes methods Attributes are simple variable x = MyClass() assignments Methods are functions – but they are attached to the class x.i Both are called with the “dot” syntax x.f() 2 Calling class methods Let’s do some experiments by calling the class method with an instance Do you need an instance created to use the class method? Why don’t we need to pass a variable when we call the class method? Do we need a variable in the class definition? The first variable for all class methods refers to the future instance which will be created 3 Class methods in two ways Class methods can be called directly from the class MyClass.f(MyClass) #you need to pass an instance of the class More frequently class methods are called on the instance x = MyClass() x.f() # self – the instance object is always passed automatically as the first argument x.f() is the same as MyClass.f(x) – it is just syntactic sugar! 4 Does it have to be called self? It does not have to be called self. Self has no special meaning in python, you can it bob if you want Please do not do that. Name it self, every time – unless you want to play a joke on someone. IDE’s are built to highlight self This is not the place to express your creativity. 5 A typical class Define an initialization method to establish attributes and startup routines Define methods which will be used by the object Good classes have all the attributes and methods related to the purpose of the class This takes practice 6 Conclusion There are two ways to call a class method The first variable of a class method is an instance of the class Always name that Place your Webcam Video here variable the self Size 100% 7 __init__ and attributes Gilad Gressel Amrita School of Engineering Introduction Initialization of a class Instance attributes Class attributes Place your Webcam Video here Size 100% 1 Initialization of a class Nearly all classes begin with an __init__ method as their first method. __init__ is the initialization method (constructor) of the class. It is automatically run when the class is instantiated It is an entirely ordinary function, it is special only that it runs automatically on creation of a class object The __dunder__ syntax is a naming convention that we will discuss later 2 __init__ routines The __init__ method is often used to accept arguments which are used to make the particulars of a class These arguments can be set as instance attributes with the self variable However other common approaches are to Set self attributes without variable arguments (or use keyword defaults) Use the variable arguments to calculate an attribute Finally, the __init__ method can be used to run other class methods or routines during the initialization of the class note that we call another class method with the self variable 3 Instance Attributes We refer to any variable declared with self.varname = as an instance attribute An instance attribute is a piece of information attached to the instantiation (creation) of a class Instance attributes allow instances to have a state, they can remember things and change over time Each instance of a class has a separate namespace and separate instance attributes in memory Example – two instances of the same class will have the same instance attribute names, but separate memory locations 4 Class attributes We can define Class attributes which persist across all classes This can be useful to define class constants, or count statistics We refer to class attributes by the Class.attribute, both within the class code and after we have left the scope Class attributes are shared by all instances of the class Updating the class attribute will update all instance attributes as well – this is special! The reverse is not true Caution: if the class attribute is mutable, it can be modified from the instance 5 Conclusion __init__ is a class method that runs on start Instance attributes are attached to the instance Class attributes are Place your Webcam Video here attached to the class Size 100% and all instances of the class 6 Class methods Gilad Gressel Amrita School of Engineering Introduction Class method syntax Using the self Place your Webcam Video here Size 100% 1 A class is just a bunch of related functions Classes are simply related functions tied together! To make the functions, you just write them in a row These are all now class “methods” (which just means they are functions that belong to a class) 2 Class method syntax A class method is identical to a function (literally) You can have as many class methods as you like They do not even need to be defined within the class (but please do) You can call class methods directly on the instance or from the class Class.method(instance) instance.method() These two are functionally the same, the second is just syntactic sugar 3 Class methods all share the first parameter self is always the first parameter of all class methods Class.method(instance) or instance.method() are identical Self is always the first variable in all class methods This “ties” together the class methods and attributes and creates our instance You can think of a class as a bunch of methods which share one single parameter – ‘self’ or the “data” 4 Methods “do” things with the class Let’s play with our car example The method can cause the car to speed up slow down honk the horn etc 5 Conclusion Class methods do things with the class You can have as many as you like They all share the first variable “self” Place your Webcam Video here Size 100% 6 __dunder__ methods Gilad Gressel Amrita School of Engineering Introduction __dunder__ means “double under” These are normal functions! They control core python functionality Place your Webcam Video here Size 100% 1 __dunder__ means “double under” A __dunder__ method in python is just a method with two underscores before the method and two underscores after the method The __ convention has no actual syntactic purpose in python – it is simply convention and for appearances Most IDE’s are programmed to highlight them differently Dunders are ugly on purpose! It’s totally OK to use them (they are not magic) 2 What do __dunders__ control? print math: +, -, *, / , >,