id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
12,300 | data hiding is software development technique specifically used in object oriented programming to hide internal object details(data membersit ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes data hiding is also known as information hiding an objects attributes may or may not be visible outside the class definition we need to name attributes with double underscore( _prefix and those attributes the are not directly visible to outsiders any variable prefix with double underscore is called private variable which is accessible only with class where it is declared examplefor data hiding class counter__secretcount= private variable def count(self)public method self __secretcount+= print("count",self __secretcountaccessible in the same class =counter( count(invoke method count(print("total count", __secretcountcannot access private variable directly outputcount count |
12,301 | file " :\python programs\class_method py"line in print("total count", __secretcountcannot access private variable directly attributeerror'counterobject has no attribute '__secretcountdata encapsulation and data abstractionwe can restrict access of methods and variables in class with the help of encapsulation it will prevent the data being modified by accident encapsulation is used to hide the value or state of structured data object inside classpreventing unauthorized parties direct access to them data abstraction refers to providing only essential information about the data to the outside worldhiding the background details of implementation encapsulation is process to bind data and functions together into single unit class while abstraction is process in which the data inside the class is the hidden from outside world in short hiding internal details and showing functionality is known as abstraction to support encapsulationdeclare the methods or variables as private in the class the private methods cannot be called by the object directly it can be called only from within the class in which they are defined any function with double underscore is called private method access modifiers for variables and methods arepublic methods variablesaccessible from anywhere inside the classin the sub classin same script file as well as outside the script file |
12,302 | two underscores examplefor access modifiers with data abstraction class student__a= #private variable = #public variable def __private_method(self)#private method print("private method is called"def public_method(self)#public method print("public method is called"print(" ",self __a#can be accessible in same class =student(print(" ", __a#generate error print(" =", bs __private_method(#generate error public_method(outputb public method is called |
12,303 | constructors are generally used for instantiating an object the task of constructors is to initialize(assign valuesto the data members of the class when an object of class is created in python the __init__(method is called the constructor and is always called when an object is created syntax of constructor declaration def __init__(self)body of the constructor examplefor creating constructor use_ _init_ method called as constructor class studentdef __init__(self,rollno,name,age)self rollno=rollno self name=name self age=age print("student object is created" =student( ,"ajay", print("roll no of student", rollnoprint("name no of student", nameprint("age no of student", age |
12,304 | student object is created roll no of student name no of studentajay age no of student programsdefine class rectangle using length and width it has method which can compute area class rectangledef __init__(self, , )self = self = def area(self)return self *self =rectangle( , print( area()output |
12,305 | getarea and getcircumference inside this class class circledef __init__(self,radius)self radius=radius def getarea(self)return *self radius*self radius def getcircumference(self)return * *self radius =circle( print("area=", getarea()print("circumference=", getcircumference()outputarea circumference types of constructorthere are two types of constructordefault constructor and parameterized constructor default constructorthe default constructor is simple constructor which does not accept any arguments its definition has only one argument which is reference to the instance being constructed |
12,306 | argumentclass studentdef __init__(self)print("this is non parameterized constructor"def show(self,name)print("hello",names =student( show("world"outputthis is non parameterized constructor hello world examplecounting the number of objects of class class studentcount= def __init__(self)student count=student count+ |
12,307 | =student(print("the number of student objects",student countoutputthe number of student objects parameterized constructorconstructor with parameters is known as parameterized constructor the parameterized constructor take its first argument as reference to the instance being constructed known as self and the rest of the arguments are provided by the programmer examplefor parameterized constructor class studentdef __init__(self,name)print("this is parameterized constructor"self name=name def show(self)print("hello",self names =student("world" |
12,308 | outputthis is parameterized constructor hello world destructora class can define special method called destructor with the help of _del_ (it is invoked automatically when the instance (objectis about to be destroyed it is mostly used to clean up non memory resources used by an instance(objectexamplefor destructor class studentdef __init__(self)print("this is non parameterized constructor"def __del__(self)print("destructor called" =student( =student(del |
12,309 | this is non parameterized constructor this is non parameterized constructor destructor called method overloadingmethod overloading is the ability to define the method with the same name but with different number of arguments and data types with this ability one method can perform different tasksdepending on the number of arguments or the types of the arguments given method overloading is concept in which method in class performs operations according to the parameters passed to it as in other language we can write program having two methods with same name but with different number of arguments or order of arguments but in python if we will try to do the same we get the following issue with method overloading in python exampleto calculate area of rectangle def area(length,breadth)calc=length*breadth print(calcto calculate area of square def area(size)calc=size*size |
12,310 | area( area( , output traceback (most recent call last)file " :\python programs\trial py"line in area( , typeerrorarea(takes positional argument but were given python does not support method overloading it is not possible to define more than one method with the same name in class in python this is because method arguments in python do not have type method accepting one argument can be called with an integer valuea string or double as shown in example exampleclass demodef print_r(self, , )print(aprint(bobj=demo(obj print_r( ,' ' |
12,311 | output in the above example same method works for two different data types it is clear that method overloading is not supported in python but that does not mean that we cannot call method with different number of arguments there are couple of alternatives available in python that make it possible to call the same method but with different number of arguments using default argumentsit is possible to provide default values to method arguments while defining method if method arguments are supplied default valuesthen it is not mandatory to supply those arguments while calling method as shown in example example method overloading with deafult arguments class demodef arguments(self, =none, =none, =none)if( !=none and !=none and !=none)print(" arguments"elif ( !=none and !=none) |
12,312 | elif !=noneprint(" argument"elseprint(" arguments"obj=demo(obj arguments("amol","kedar","sanjay"obj arguments("amit","rahul"obj arguments("sidharth"obj arguments(output arguments arguments argument arguments |
12,313 | overloading class operationdef add(self, , )return + op=operation(to add two integer numbers print("addition of integer numbers",op add( , )to add two floating numbers print("addition of integer numbers",op add( , )to add two strings print("addition of stings",op add("hello","world")outputaddition of integer numbers addition of integer numbers addition of stingshelloworld |
12,314 | the mechanism of designing and constructing classes from other classes is called inheritance inheritance is the capability of one class to derive or inherit the properties from some another class the new class is called derived class or child class and the class from which this derived class has been inherited is the base class or parent class the benefits of inheritance are it represents real-world relationships well it provides reusability of code we don' have to write the same code again and again alsoit allows us to add more features to class without modifying it it is transitive in naturewhich means that if class inherits from another class athen all the subclasses of would automatically inherit from class |
12,315 | class aproperties of class class ( )class inheriting property of class more properties of class example example of inheritance without using constructor class vehicle#parent class name="marutidef display(self)print("name",self nameclass category(vehicle)drived class price= def disp_price(self)print("price",self pricecar =category(car display(car disp_price( |
12,316 | namemaruti price example example of inheritance using constructor class vehicle#parent class def __init__(self,name,price)self name=name self price=price def display(self)print("name",self nameclass category(vehicle)drived class def __init__(self,name,price)vehicle __init__(self,name,price#pass data to base constructor def disp_price(self)print("price",self pricecar =category("maruti", car display(car disp_price( |
12,317 | car display(car disp_price(outputnamemaruti price namehonda price multilevel inheritancein multilevel inheritancefeatures of the base class and the derived class are further inherited into the new derived class this is similar to relationship representing child and grandfather |
12,318 | class aproperties of class class ( )class inheriting property of class more properties of class class ( )class inheriting property of class thusclass also inherits properties of class more properties of class example python program to demonstrate multilevel inheritance #mutilevel inheritance class def display (self)print("class "class ( )def display (self)print("class "class ( ) |
12,319 | print("class " = ( display ( display ( display (outputclass class class example python program to demonstrate multilevel inheritance base class class grandfathergrandfathername ="def grandfather(self)print(self grandfathername |
12,320 | class father(grandfather)fathername "def father(self)print(self fathernamederived class class son(father)def parent(self)print("grandfather :"self grandfathernameprint("father :"self fathernamedriver' code son( grandfathername "srinivass fathername "ankushs parent(outputgrandfather srinivas |
12,321 | multiple inheritancewhen class can be derived from more than one base classes this type of inheritance is called multiple inheritance in multiple inheritanceall the features of the base classes are inherited into the derived class syntaxclass avariable of class functions of class class bvariable of class functions of class class ( , ) |
12,322 | more properties of class examplepython program to demonstrate multiple inheritance base class class fatherdef display (self)print("father"base class class motherdef display (self)print("mother"derived class class son(father,mother)def display (self)print("son" son( display ( display ( display ( |
12,323 | son mother father hierarchical inheritancewhen more than one derived classes are created from single base this type of inheritence is called hierarchical inheritance in this programwe have parent (baseclass and two child (derivedclasses example python program to demonstrate hierarchical inheritance base class class parent |
12,324 | print("this function is in parent class "derived class class child (parent)def func (self)print("this function is in child "derived class class child (parent)def func (self)print("this function is in child "object child (object child (object func (object func (object func (object func ( |
12,325 | this function is in parent class this function is in child this function is in parent class this function is in child method overridingmethod overriding is an ability of class to change the implementation of method provided by one of its base class method overriding is thus strict part of inheritance mechanism to override method in base classwe must define new method with sam name and same parameters in the derived class overriding is very important part of oop since it is feature that makes inheritance exploit its full power through method overriding class may "copyanother classavoiding duplicated code and at the same time enhance or customize part of it examplefor method overriding class adef display(self)print("this is base class" |
12,326 | def display(self)print("this is derived class"obj= (instance of child obj display(child class overriden method outputthis is derived class using super(methodthe super(method gives you access to methods in super class from the subclass that inherits from it the super(method returns temporary object of the superclass that then allows you to call that superclass' method examplefor method overriding with super(class adef display(self)print("this is base class"class ( )def display(self)super(display( |
12,327 | obj= (instance of child obj display(child class overriden method outputthis is base class this is derived class composition classesin composition we do not inherit from the base class but establish relationship between classes through the use of instance variables that are references to other objects composition means that an object knows another object and explicitly delegates some tasks to it while inheritance is implicitcomposition is explicit in python we use composition when we want to use some aspects of another class without promising all of the features of that other class syntaxclass genericclassdefine some attributes and methods |
12,328 | instance_variable_of_generic_class=genericclass #use this instance somewhere in the class some_method(instance_varable_of_generic_classfor examplewe have three classes emailgmail and yahoo in email class we are referring the gmail and using the concept of composition exampleclass gmaildef send_email(self,msg)print("sending '{}from gmailformat(msg)class yahoodef send_email(self,msg)print("sending '{}from yahooformat(msg)class emailprovider=gmail(def set_provider(self,provider)self provider=provider def send_email(self,msg) |
12,329 | client =email(client send_email("hello"client set_provider(yahoo()client send_email("hello"outputsending 'hellofrom gmail sending 'hellofrom yahoo customization via inheritance specializing inherited methodsthe tree-searching model of inheritance turns out to be great way to specialize systems because inheritance finds names in subclasses before it checks superclassessubclasses can replace default behavior by redefining the superclass' attributes in factyou can build entire systems as hierarchies of classeswhich are extended by adding new external subclasses rather than changing existing logic in place the idea of redefining inherited names leads to variety of specialization techniques |
12,330 | instancesubclasses completelyprovide attributes that may replace inherited attributes to superclass expects findand extend superclass methods by calling back to the superclass from an overridden method examplefor specilaized inherited methods class "parent class#parent class def display(self)print("this is base class"class ( )"child class#derived class def display(self) display(selfprint("this is derived class"obj= (#instance of child obj display(#child calls overridden method outputthis is base class this is derived class |
12,331 | behavior rather than replacing it completely extension is the only way to interface with superclass the following program defines multiple classes that illustrate variety of common techniques super defines method function and delegate that expects an action in subclass inheritor doesn' provide any new namesso it gets everything defined in super replacer overrides super' method with version of its own extender customizes super' method by overriding and calling back to run the default provider implements the action method expected by super' delegate method |
12,332 | class superdef method(self)print("in super method"#default behavior def delegate(self)self action(#expected to be defined class inheritor(super)pass class replacer(super)#replace method completely def method(self)print("in replacer method"class extender(super)#extend method behavior def method(self)super method(selfprint("in extender method"class provider(super)fill in required method def action(self)print("in provider action"for klass in (inheritor,replacer,extender) |
12,333 | programming in python object oriented programming is way of computer programming using the idea of "objectsto represents data and methods it is alsoan approach used for creating neat and reusable code instead of redundant one |
12,334 | procedural oriented programming object-oriented programming (oopprocedural-oriented programming (popit is bottom-up approach it is top-down approach program is divided into objects program is divided into functions makes use of access modifiers 'public'private'protecteddoesn' use access modifiers it is more secure it is less secure object can move freely within member functions data can move freely from function to function within programs it supports inheritance it does not support inheritance |
12,335 | class is collection of objects or you can say it is blueprint of objects defining the common attributes and behavior now the question ariseshow do you do thatclass is defined under "classkeyword exampleclass class ()/class is the name of the class |
12,336 | exampleclass employee()def __init__(self,name,age,id,salary)//creating function self name name /self is an instance of class self age age self salary salary self id id emp employee("harshit", , , //creating objects emp employee("arjun", , , print(emp __dict__)//prints dictionary |
12,337 | methodologiesinheritance polymorphism encapsulation abstraction |
12,338 | ever heard of this dialogue from relatives "you look exactly like your father/motherthe reason behind this is called 'inheritancefrom the programming aspectit generally means "inheriting or transfer of characteristics from parent to child class without any modificationthe new class is called the derived/child class and the one from which it is derived is called parent/base class |
12,339 | single level inheritance enables derived class to inherit characteristics from single parent class |
12,340 | class employee ()://this is parent class def __init__(selfnameagesalary)self name name self age age self salary salary class childemployee(employee )://this is child class def __init__(selfnameagesalary,id)self name name self age age self salary salary self id id emp employee ('harshit', , print(emp ageoutput |
12,341 | multi-level inheritance enables derived class to inherit properties from an immediate parent class which in turn inherits properties from his parent class exampleclass employee()://super class def __init__(self,name,age,salary)self name name self age age self salary salary class childemployee (employee)://first child class def __init__(self,name,age,salary)self name name self age age self salary salary |
12,342 | def __init__(selfnameagesalary)self name name self age age self salary salary emp employee('harshit', , emp childemployee ('arjun', , print(emp ageprint(emp ageoutput , |
12,343 | hierarchical level inheritance enables more than one derived class to inherit properties from parent class exampleclass employee()def __init__(selfnameagesalary)self name name self age age self salary salary //hierarchical inheritance |
12,344 | def __init__(self,name,age,salary)self name name self age age self salary salary class childemployee (employee)def __init__(selfnameagesalary)self name name self age age self salary salary emp employee('harshit', , emp employee('arjun', , |
12,345 | multiple level inheritance enables one derived class to inherit properties from more than one base class exampleclass employee ()//parent class def __init__(selfnameagesalary)self name name self age age self salary salary |
12,346 | def __init__(self,name,age,salary,id)self name name self age age self salary salary self id id class childemployee(employee ,employee )def __init__(selfnameagesalary,id)self name name self age age self salary salary self id id emp employee ('harshit', , emp employee ('arjun', , , |
12,347 | you all must have used gps for navigating the routeisn' it amazing how many different routes you come across for the same destination depending on the trafficfrom programming point of view this is called 'polymorphismit is one such oop methodology where one task can be performed in several different ways to put it in simple wordsit is property of an object which allows it to take multiple forms |
12,348 | compile-time polymorphism run-time polymorphism |
12,349 | compile-time polymorphism also called as static polymorphism which gets resolved during the compilation time of the program one common example is "method overloading |
12,350 | class employee ()def name(self)print("harshit is his name"def salary(self)print(" is his salary"def age(self)print(" is his age"class employee ()def name(self)print("rahul is his name"def salary(self)print(" is his salary"def age(self)print(" is his age" |
12,351 | obj name(obj salary(obj age(obj_emp employee (obj_emp employee (func(obj_emp func(obj_emp outputharshit is his name is his salary is his age rahul is his name is his salary is his age |
12,352 | run-time polymorphism is alsocalled as dynamic polymorphism where it gets resolved into the run time one common example of run-time polymorphism is "method overriding |
12,353 | class employee()def __init__(self,name,age,id,salary)self name name self age age self salary salary self id id def earn(self)pass class childemployee (employee)def earn(self)//run-time polymorphism print("no money" |
12,354 | an introduction to oop using pythonpart --basic principles and syntax what is object-oriented programming object-oriented programming (oop)deservedly or nothas something of reputation as an obtuse and mysterious way of programming you may have heard of itand even heard that it is powerful way of writing programsbut you probably haven' heard clear and concise description of how it works to help you write better aos programs unfortunatelyi also cannot give you clear and concise description of how oop works to help you program the problem is not that cannot describe to you what an object is or give you definition of oopbut rather that any description of the mechanics and use of oop does not really capture how oop makes your life easier as scientist programmer it' like thinking that description of oil pigments and poplar surfaces will somehow enable you to "gethow the mona lisa works for both oop and artyou can' describe the forest in terms of the trees reallythe only way know of to convey how oop enables atmospheric and oceanic scientists to do better science using computer is to give you many examples of its use soin this 'll do just that after brief description of the mechanics of oopwe'll look at some simple examples and work through some more complex examplesincluding examples from the atmospheric and oceanic sciences through these examplesi hope to describe both how to write object-oriented programs as well as why objectoriented programs work the way they do |
12,355 | procedural vs object-oriented programming one good way of describing something new is to compare it with something old most atmospheric and oceanic scientists have had experience with procedural programmingso we'll start there procedural programs look at the procedural world in terms of two entities"dataand "functions in procedural conprograms have data and textthe two entities are separate from each other function takes data as functions as input and returns data as output additionallythere' nothing customizable separate about function with respect to data as resultthere are no barriers to entities using function on various types of dataeven inappropriately in the real worldhoweverwe don' think of things or objects as having these two features (data and functionsas separate entities that isreal world objects are not (usuallymerely data nor merely functions real world real world objects have objects instead have both "stateand "behaviors for instancepeople have states and state (tallshortetc and behavior (playing basketballrunningetc )often behaviors both at the same timeandof coursein the same person the aim of object-oriented programming is to imitate this in terms of softwareso that "objectsin software have two entities attached to themstates and behavior this makes the conceptual leap from real-world to programs (hopefullyless of leap and more of step as resultwe can more easily implement ideas into instructions computer can understand the nuts and bolts of objects what do objects consist ofan object in programming is an entity or "variablethat has two entities attached to itdata and things that act on that data the data are called attributes of the objectand the functions attached to the object that can act on the data are called methods of the object importantlyobjects are made up of you design these methods to act on the attributesthey aren' random funcattributes and tions someone has attached to the object in contrastin procedural programmethods mingvariables have only one set of datathe value of the variablewith no functions attached to the variable how are objects definedin the real worldobjects are usually examples or specific realizations of some class or type for instanceindividual people are specific realizations of the class of human beings the specific reobject instances are alizationsor instancesdiffer from one another in details but have the same specific pattern for peoplewe all have the same general shapeorgan structureetc realizations of in oopthe specific realizations are called object instanceswhile the coma class mon pattern is called class in pythonthis common pattern or template is defined by the class statement |
12,356 | soin summaryobjects are made up of attributes and methodsthe structure of common pattern for set of objects is called its classand specific realizations of that pattern are called "instances of that class recall that all the python "variableswe introduced earlier are actually objects (in factbasically everything in python is an object let' look at number of different python objects to illustrate how objects work example of how objects workstrings python strings (like nearly everything else in pythonare objects thusbuilt into pythonthere (implicitlyis class definition of the string classand every time you create stringyou are using that definition as your template that template defines both attributes and methods for all string objectsso whatever string you've createdyou have that set of data and functions attached to your string which you can use let' look at specific caseexample (viewing attributes and methods attached to strings and trying out few methods)in the python interpretertype ina "hellonow typedir(awhat do you seetype title(and upper(and see what you get solution and discussionthe dir(acommand gives list of (nearlyall the attributes and methods attached to the object awhich is the string the dir "hellonote that there is more data attached to the object than just the command word "hello" the attributes doc and class also show up in shows an object' the dir listing methods can act on the data in the object thusa title(applies the attributes and title method to the data of and returns the string "helloin title case methods ( the first letter of the word capitalized) upper(applies the upper method to the data of and returns the string all in uppercase notice these methods do not require additional input arguments between the parenthesisbecause all the data needed is already in the object ( "hello" |
12,357 | let' do quick review of syntax for objects firstto refer to attributes review of syntax for or methods of an instanceyou add period after the object name and then objects put the attribute or method name to set an attributethe reference should be on the lefthand side of the equal signthe opposite is the case to read an attribute method calls require you to have parentheses after the namewith or without argumentsjust like function call finallymethods can produce return value (like function)act on attributes of the object in-placeor both exercise on how objects workstrings exercise (strings and how objects work)in the python interpretertype ina 'the rain in spain given string create new string that is but all in uppercase is changed when you create how would you test to see whether is in uppercasethat ishow could you return boolean that is true or false depending on whether is uppercase how would you calculate the number of occurrences of the letter "nin athe upperisupperand count string methods solution and discussionhere are my solutions upper( nothe upper method' return value is used to create bthe value of is not changed in place use the isupper method on the string objecti isupper(will return true or falseaccordingly count(' ' |
12,358 | example of how objects workarrays while lists have their usesin scientific computingarrays are the central object most of our discussion of arrays has focused on functions that create and act on arrays arrayshoweverare objects like any other object and have attributes and methods built-in to themarrays are more than just sequence of numbers let' look at an example list of all the attributes and methods of an array objectexample (examining array object attributes and methods)in the python interpretertype ina reshape( arange( )( , )now typedir(awhat do you seebased on their namesand your understanding of what arrays arewhat do you think some of these attributes and methods dosolution and discussionthe dir command should give you list of lot of stuff ' not going to list all the output here but instead will discuss the output in general terms we first notice that there are two types of attribute and method namesthose with double-underscores in front and in back of the name and those without any preor post-pended double-underscores we consider each type of name in turn very few double-underscore names sound like data the doc doublevariable is one such attribute and refers to documentation of the object most underscore of the double-underscore names suggest operations on or with arrays ( attribute and adddivetc )which is what they arethose names are of the methods of the method array object that define what python will do to your data when the interpreter names sees "+""/"etc thusif you want to redefine how operators operate on arraysyou can do so it is just matter of redefining that method of the object that being saidi do notin generalrecommend you do so in pythonthe double-underscore in front means that attribute or method is "very prisinglevate ( variable with single underscore in front is privatebut not as underscore private as double-underscore variable that is to sayit is an attribute or attribute and method that normal users should not accesslet alone redefine python does method nothoweverdo much to prevent you from doing soso advanced users who names need to access or redefine those attributes and methods can do so |
12,359 | the non-double-underscore names are names of "publicattributes and methodsi attributes and methods normal users are expected to access public attributes and and (possiblyredefine number of the methods and attributes of are methods duplicates of functions (or the output of functionsthat act on arrays ( transposet)so you can use either the method version or the function version and now let' look at some examples of accessing and using array object attributes and methodsexample (using array attributes and methods)in the python interpretertype ina reshape( arange( )( , )print astype(' 'print shape print cumsum(print what do each of the print lines doare you accessing an attribute or method of the array?solution and discussionthe giveaway as to whether we are accessing attributes or calling methods is whether there are parenthesis after the nameif notit' an attributeotherwiseit' method of courseyou could type how to tell whether you the name of the method without parentheses followingbut then the interare accessing preter would just say you specified the method itselfas you did not call the an attribute or methoda method print astype <built-in method astype of numpy ndarray object at ( manually added linebreak in the above screenshot to fit it on the page that is to saythe above syntax prints the method itselfsince you can' meaningfully print the method itselfpython' print command just says "this is method the astype call produces version of array that converts the values of into single-character strings the shape attribute gives the shape of |
12,360 | the array the cumsum method returns flattened version of the array where each element is the cumulative sum of all the elements before finallythe object attribute is the transpose of the array versions of astypeshapeand cumsum while it' nice to have bunch of array attributes and methods attached to the array objectin practicei find seldom access array attributes and find it easier to use numpy functions instead of the corresponding array methods one exception with regards to attributes is the dtype char attributethat' very useful since it tells you the type of the elements of the array (see example for more on dtype char exercise on how objects workarrays exercise (more on using array attributes and methods)for all these exercises (except for the first one)do not use numpy module functionsonly use attributes or methods attached to the arrays (do these in ordersince each builds on the preceding commands create column row floating point array named the array can have any numerical values you wantas long as all the elements are not all identical create an array that is copy of but is -dnot - turn into column row arrayin place create an array where you round all elements of to decimal place solution and discussionhere are array methods that one can use to the accomplish the exercisesreshape reshape( arange( dtype=' ')( , ) ravel( resize(( , ) round( ravelresizeand round function and methods |
12,361 | remembermethods need to be called or else they don' do anythingincluding the parentheses to specify the calling argument list tells the interpreter you're calling the method in terms of the "outputof the methodsome methods act like functionreturning their output as return value other methods do their work "in-place,on the object the method is attached tothose methods do not typically have return value the resize method is an example of method that operates on the data in-placewhich is why there is no equal sign (for assignmentassociated with the method call you can also make method operate on an object in-place as well as output return value defining your own class we had said that all objects are instances of classand in the preceding exampleswe looked at what made up string and array instanceswhich tells us something about the class definitions for those two kinds of objects how would we go about creating our own class definitionsclass definitions start with class statement the block following the defining class line is the class definition within the definitionyou refer to the inclass using class stance of the class as self sofor examplethe instance attribute data is called self data in the class definitionand the instance method named calculate is called self calculate in the class definition ( it is called by self calculate()if it does not take any argumentsmethods are defined using the def statement the first argument in any defining methods and method is selfthis syntax is how python tells method "make use of all the self the previously defined attributes and methods in this instance howeverargument you never type self when you call the method usuallythe first method you define will be the init method this the init method method is called whenever you create an instance of the classand so you usually put code that handles the arguments present when you create (or instantiatean instance of class and conducts any kind of initialization for the object instance the arguments list of init is the list of arguments passed in to the constructor of the classwhich is called when you use the class name with calling syntax whewthis is all very abstract we need an examplehere' one this statement is not entirely correct if you do set another variableby assignmentto such method callthat lefthand-side variable will typically be set to none |
12,362 | example (example of class definition for book class)this class provides template for holding and manipulating information about book the class definition provides single method (besides the initialization methodthat returns formatted bibliographic reference for the book the code below gives the class definition and then creates two instances of the class (note line continuations are added to fit the code on the page) class book(object)def __init__(selfauthorlastauthorfirsttitleplacepublisheryear)self authorlast authorlast self authorfirst authorfirst self title title self place place self publisher publisher self year year def write_bib_entry(self)return self authorlast 'self authorfirst 'self title 'self place 'self publisher 'self year beauty book"dubay""thomas"the evidential power of beauty"san francisco"ignatius press"" pynut book"martelli""alex"python in nutshell"sebastopolca" 'reilly mediainc "" can you explain what each line of code doessolution and discussionline begins the class definition by conventhe object tionclass names follow the capwords convention (capitalize the first letter object and of every wordthe argument in the class statement is special object called inheritance |
12,363 | object this has to do with the oop idea of inheritancewhich is topic beyond the scope of this book suffice it to say that classes you create can inherit or incorporate attributes and methods from other classes base classes (class that do not depend on other classesinherit from objecta special object in python that provides the foundational tools for classes notice how attributes and methods are definedsetand used in the class definitionperiods separate the instance name self from the attribute and method name so the instance attribute title is called self title in the class definition when you actually create an instancethe instance name is the name of the object ( beautypynut)so the instance attribute title of the instance beauty is referred to as beauty titleand every instance attribute is separate from every other instance attribute ( beauty title and pynut title are separate variablesnot aliases for one anotherthusin lines - assign each of the positional input parameters in the def init line to an instance attribute of the same name once assignedthese attributes can be used anywhere in the class definition by reference to selfas in the definition of the write bib entry method speaking of whichnote that the write bib entry method is called with no input parametersbut in the class definition in lines - still need to provide it with self as an input that waythe method definition is able to make use of all the attributes and methods attached to self in lines - create an instance beauty of the book class note how the arguments that are passed in are the same arguments as in the def init argument list in the last four linesi create another instance of the book class (the code of this example is in course files/code files in file called bibliog py now that we've seen an example of defining classlet' look at an example of using instances of the book class to help us better understand what this class doesexample (using instances of book)consider the book definition given in example here are some questions to test your understanding of what it does how would you print out the author attribute of the pynut instance (at the interpreterafter running the file) |
12,364 | if you type print beauty write bib entry(at the interpreter (after running the file)what will happen how would you change the publication year for the beauty book to " "solution and discussionmy answers typeprint pynut author remember that once an instance of book is createdthe attributes are attached to the actual instance of the classnot to self the only time self exists is in the class definition you will print out the the bibliography formatted version of the information in beauty typebeauty year " remember that you can change instance attributes of classes you have designed just like you can change instance attributes of any classjust use assignment (there is also function called setattr that you can use to assign attributes 'll talk about setattr in section exercise on defining your own class exercise (the book class and creating an article class)here are the tasks create another instance of the book class using book of your choosing (or make up bookexecute the write bib entry method for that instance to check if it looks like what you wanted add method make authoryear to the class definition that will create an attribute authoryear and will set that attribute to string that has the last name of the author and then the year in parenthesis for instancefor the beauty instancethis method will set authoryear to 'dubay ( )the method should not have return statement create an article class that manages information about articles it will be very similar to the class definition for bookexcept publisher |
12,365 | and place information will be unneeded and article titlevolume numberand pages will be needed make sure this class also has the methods write bib entry and make authoryear solution and discussionhere are my answers here' another instance of bookwith call to the write bib entry methodmadeup book("doe""john""good book""chicago""me press"" "print madeup write_bib_entry(this code will print the following to the screendoejohngood bookchicagome press the entire book class definitionwith the new method (and line continuations added to fit the code on the page)is class book(object)def __init__(selfauthorlastauthorfirsttitleplacepublisheryear)self authorlast authorlast self authorfirst authorfirst self title title self place place self publisher publisher self year year def make_authoryear(self)self authoryear self authorlast '(self year +') def write_bib_entry(self)return self authorlast 'self authorfirst 'self title 'self place 'self publisher 'self year |
12,366 | the new portion is lines - none of the rest of the class definition needs to change the class definition for article (with line continuations added to fit the code on the pageis class article(object)def __init__(selfauthorlastauthorfirstarticletitlejournaltitlevolumepagesyear)self authorlast authorlast self authorfirst authorfirst self articletitle articletitle self journaltitle journaltitle self volume volume self pages pages self year year def make_authoryear(self)self authoryear self authorlast (self year +') def write_bib_entry(self)return self authorlast 'self authorfirst (self year ')'"self articletitle ',self journaltitle 'self volume 'self pages this code looks nearly the same as that for the book classwith these exceptionssome attributes differ between the two classes (booksfor instancedo not have journal titlesand the method write bib entry is different between the two classes (to accommodate the different formatting between article and book bibliography entriessee bibliog py in course files/code files for the code |
12,367 | programming easier making classes work together to make complex programming easier so in our introduction to object-oriented programming (oop)we found out summary of introduction that objects hold attributes (dataand methods (functions that act on datato oop together in one related entity realizations of an object are called instances the template or form for an object is called classso realizations are instances of class in pythonthe class statement defines the template for object instances in the class statementinstances of the class are called self once real instance of the class is createdthe instance (objectname itself is "substitutedin for self but so whatit seems like classes are just different way of organizing data and functionsinstead of putting them in libraries (or modules)you put them in class if you're thinking that this isn' that big of deali would agree that it isn' big dealif all you do in program is write single class with single instance of that classin that caseoop does not buy you very much the real power of ooprathercomes when objects are used in conjunction with other classes by properly designing your set of classesthe object-oriented structure can make your code much simpler to write and understandeasier to debugand less prone to error in the remaining sections of the we'll look at two case studies illustrating the use of oop in this manner the first case study extends our book and article classes by examining the more general program of how to create bibliography in the second case studywe consider how to create class for geosciences work that "managesa surface domain case study the bibliography example the book and article classes we wrote earlier manage information related to books and articles in this case studywe make use of book and article to help us implement one common use of book and article informationthe creation of bibliography in particularwe'll write bibliography class that will manage bibliographygiven instances of book and article objects structuring the bibliography class since bibliography consists of list of (usually formattedbook and article entrieswe will want our bibliography class to contain such list thus |
12,368 | the bibliography class hasas its main attributea list of entries which are instances of book and article classes rememberinstances of book and article can be thought of as books and articlesthe instances are the "objectsthat specific books and articles are nextwe write methods for bibliography that can manipulate the list of book and article instances to that endthe first two methods we write for bibliography will do the followinginitialize an instance of the classrearrange the list alphabetically based upon last name then first name the initialization method is called init (as always)and the rearranging method will be called sort entries alpha here is the code import operator class bibliography(object)def __init__(selfentrieslist)self entrieslist entrieslist def sort_entries_alpha(self)tmp sorted(self entrieslistkey=operator attrgetter('authorlast''authorfirst')self entrieslist tmp del tmp let' talk about what this code does in the init methodthere is only single argumententrieslist this is the list of book and article instances that are being passed into an instance of the bibliography class the init method assigns the entrieslist argument to an attribute of the same name lines - define the sort entries alpha methodwhich sorts the entrieslist attribute and replaces the old entrieslist attribute with the sorted version the method uses the built-in sorted functionwhich takes keyword parameter key that gives the key used for sorting the argument of sorted how is that key generatedthe attrgetter functionwhich is part of the the operator modulegets the attributes of the names listed as arguments attrgetter to attrgetter out of the elements of the item being sorted (note that the function and attribute names passed into attrgetter are stringsand thus you refer to the sorted attributes of interest by their string namesnot by typing in their names this makes the program much easier to write in our exampleattrgetter has two argumentssorted indexes self entrieslist by the attrgetter' first argument attribute name first then the second |
12,369 | note that at the end of the sort entries alpha method definitioni use the del command to make sure that tmp disappears need to do this because lists are mutableand python assignment is by reference not value (see for more discussion on reference vs valueif do not remove tmpthe tmp might float around as reference to the entrieslist attributeit shouldn'tbut ' paranoid so explicitly deallocate tmp to make sure some final commentsfirstif you would like to read more on sorting in pythonplease see sorted function is very versatile secondthere are some diagnostics at the end of bibliog py that are run if you typepython bibliog py from the operating system command line this is one way of writing very basic test to make sure that module works (python has solid unit testing basic testing of programs framework in the form of the unittest moduleif you're interested in something more robust these diagnosticshoweverare not implemented if you import bibliog py as module this is due to the conditionalif name =main 'which is true only if the module is being run as main programi by the python command if you import the module for use in another moduleby using importthe variable name will not have the string value main 'and the diagnostics will not execute what sort entries alpha illustrates about oop let' pause to think for moment about the method sort entries alpha what have we just donefirstwe sorted list of items that are totally differently structured from each other based on two shared types of data (attributessecondwe did the sort using sorting function that does not care about the details of the items being sortedonly that they had these two shared types of data in other wordsthe sorting function doesn' care about the source type ( articlebook)only that all source types have the attributes authorlast and authorfirst this doesn' seem that big dealbut think about how we would have had comparing oop vs to do it in traditional procedural programming firsteach instance would procedural for have been an arraywith label of what kind of source it isfor instancea sorting example nature_array ["article""smith""jane""my nobel prize-winning paper""nature"" "" - "" " |
12,370 | the procedural sorting function you' write would need know which elements you want to sort with (here the second and third elements of the arraybut the index for every array of data would potentially be differentdepending on where in the array that data is stored for that source type thusin your sorting functionyou' need to run multiple if tests (based on the source typeto extract the correct field in the array to sort by butif you changed the key you're sorting by ( from the author' name to the date of publication)you would have to change the element index you're sorting against this means manually changing the code of the if tests in your sorting function it' easy to make such manual code change and test that the change worksif you only have few source types ( articles and books)but what if you have tens or hundreds of source typeswhat nightmareand as you make all those code changesthink of the number of possible bugs you may introduce just from keystroke errors alonebut in object-oriented programmingyou can switch the sorting key at will and have an infinite number of source types without any additional code changes ( no if tests to changethis is the power of oop over procedural programmingcode structured using an oop framework naturally results in programs that are much more flexible and extensibleresulting in dramatically fewer bugs exercise in extending the bibliography class exercise (writing out an alphabetically sorted bibliography)since we programmed book and article with write bib entry methodslet' take advantage of that write method write bibliog alpha for the bibliography class we just created that actually writes out bibliography (as stringwith blank lines between the entrieswith the entries sorted alphabetically by author name the bibliography should be returned using return statement in the method some hintselements of list do not have to all have the same type for loops do not only loop through lists of numbers but through any iterable this includes lists of any sortincluding lists of objects (such as book and article instances strings are immutableso you cannot append to an existing string insteaddo reassignment combined with concatenation ( = + |
12,371 | to initialize stringin order to grow it in concatenation steps such as in for loopstart by setting the string variable to an empty string (which is just ''solution and discussionhere is the solution for the entire classwith the new method included import operator class bibliography(object)def __init__(selfentrieslist)self entrieslist entrieslist def sort_entries_alpha(self)tmp sorted(self entrieslistkey=operator attrgetter('authorlast''authorfirst')self entrieslist tmp del tmp def write_bibliog_alpha(self)self sort_entries_alpha(output 'for ientry in self entrieslistoutput output ientry write_bib_entry('\ \nreturn output[:- the only code that has changed compared to what we had previously is the write bibliog alpha methodlet' talk about what it does line defines the methodbecause self is the only argumentthe method is called with an empty argument list the next line calls the sort entries alpha method to make sure the list that is stored in the entrieslist attribute is alphabetized nextwe initialize the output string output as an empty string when the "+operator is usedpython will then use string concatenation on it lines - run for loop to go through all elements in the list entrieslist the output of write bib entry is added one entry at timealong with two linebreaks after it finallythe entire string is output except for the final two linebreaks (remember that strings can be manipulated using list slicing syntax |
12,372 | work--surface domain management what the write bibliog alpha method illustrates about oop here toolet' ask how would we have written function that wrote out an alphabetized bibliography in procedural programmingprobably something like the following sketchdef write_bibliog_function(arrayofentries)[open output filefor in xrange(len(arrayofentries))ientryarray arrayofentries[iif ientryarray[ "article"[call function for bibliography entry for an articleand save to output fileelif ientryarray[ ="book"[call function for bibliography entry for an bookand save to output file[close output filethis solution sketch illustrates how in procedural programming we are stuck writing if tests in the bibliography writing function to make sure we format each source entry correctlydepending on source type ( articlebookin factfor every function that deals with multiple source typeswe need this tree of if tests if you introduce another source typeyou need to add another if test in all functions where you have this testing tree this is recipe for disasterit is exceedingly easy to inadvertently add an if test in one function but forget to do so in another functionetc in contrastwith objectsadding another source type requires no code changes or additions the new source type just needs write bib entry method defined for it andsince methods are designed to work with the attributes of their classthis method will be tailor-made for its data so much easier case study creating class for geosciences work--surface domain management think the bibliography example in section does good job of illustrating what object-oriented programming gives you that procedural programming |
12,373 | work--surface domain management cannot also like the example because all of us have had to write bibliographyand the idea of "sources(booksarticlesvery nicely lends itself to being thought of as an "object but can the oop way of thinking help us in decomposing geosciences problemin this sectionwe consider class for managing surface domains ( latitude-longitude domaini present the task of defining the class as an exercise and give two possible solutions the exercise and solutionswhile valuable in and of themselvesoffer nice illustration of how oop enables atmospheric and oceanic scientists to write more concise but flexible code for handling scientific calculations exercise (defining surfacedomain class)define class surfacedomain that describes surface domain instances the domain is land or ocean surface region whose spatial extent is described by latitude-longitude grid the class is instantiated when you provide vector of longitudes and latitudesthe surface domain is regular grid based on these vectors surface parameters ( elevationtemperatureroughnessetc can then be given as instance attributes the quantities are given on the domain grid in additionin the class definitionprovide an instantiation method that saves the input longitude and latitude vectors as appropriately named attributes and creates - arrays of the shape of the domain grid which have the longitude and latitude values at each point and saves them as private attributes ( their names begin with single underscore |
12,374 | work--surface domain management hintan example may help with regards to what ' asking for with respect to the - arrays if lon= arange( and lat= arange( )then the lonall instance attribute would be[[ [ [ [ ]and the latall instance attribute would be[[ [ [ [ ]solution and discussionthe two solutions described below (with the second solution commented outare in course files/code files in the file surface domain pyhere' the solution using for loops import numpy as class surfacedomain(object)def __init__(selflonlat)self lon array(lonself lat array(lat shape ( size(self lat) size(self lon)self _lonall zeros(shape ddtype=' 'self _latall zeros(shape ddtype=' 'for in xrange(shape [ ])for in xrange(shape [ ])self _lonall[ ,jself lon[jself _latall[ ,jself lat[ilines - guarantee that lon and lat are numpy arraysin case lists or tuples are passed in and here' simpler and faster solution using the meshgrid function in using numpy instead of the for loopsmeshgrid |
12,375 | work--surface domain management import numpy as class surfacedomain(object)def __init__(selflonlat)self lon array(lonself lat array(lat[xallyalln meshgrid(self lonself latself _lonall xall self _latall yall del xallyall sowhat does this surfacedomain class illustrate about oop applied to the geosciencespretend you have multiple surfacedomain instances that you want to communicate to each otherwhere the bounds of one are taken from (or interpolated withthe bounds of anothere calculations for each domain instance are farmed out to separate processorand you're stitching domains togetherin the above schematicgray areas are surfacedomain instances and the thickdark lines are the overlapping boundaries between the domain instances in procedural programmingto manage this set of overlapping domainscomparing oop vs you might create grand domain encompassing all points in all the domains procedural for to make an index that keeps track of which domains abut one another the subdomain index records who contributes data to these boundary regions alternatelymanagement you might create function that processes only the neighboring domainsbut example this function will be called from scope that has access to all the domains ( via common blockbutto manage this set of overlapping domainsyou don' really need such global view nor access to all domains in facta global index or common block means that if you change your domain layoutyou have to hand-code change to your index/common block ratherwhat you actually need is only to be able to interact with your neighbor so why not just write method that takes your neighboring surfacedomain instances as arguments |
12,376 | class account(object)'' class for objects representing an account ''methods def withdraw(selfamount)self balance -amount def deposit(selfamount)self balance +amount def print_info(self)print("balance:"self balanceif __name__ ="__main__"annesacc account(annesacc balance annesacc deposit( annesacc withdraw( annesacc print_info(the methods deposit(selfamount)withdraw(selfamountand print info(selfare instance methods of the account class this means that they are designed to operate on objects that have been created from this class technicallyinstance methods are required to have first parameter which is called self (it could be called something elsetoobut self is very strong convention in pythonthe following image shows that we have an objectannesaccwhich is linked to the class account the balance attribute is only available at the particular objectbut the methods that have been defined in the class are available in the class we can call the class' methods 'on an objectusing the dot notationannesacc deposit( in the code written for the classhoweverthe method looks like thisdeposit(selfamountit has two parametersbut we called it only with one (amountso why is thatthe following happens herepython knows that annesacc is an object of the account class (because we created the object by calling the classpython executes the deposit(selfamountmethod of the account class and assigns the object on which the method was called to the self parameter this means that the following two lines of code are equivalent annesaccount deposit( account deposit(annesaccount annemarie friedrichcis lmu munchenws / |
12,377 | when operating on instance objectsyou should always use the first waybecause it leaves the job to look up the class to python and your code will be more flexible this will become clear later when we talk about inheritance constructors are useful for initialization the code for the class as written above is not very robust it does not ensure that the account object actually has balance attribute before trying to print it out if we just add the following two lines of code to the main programpython gives us an errorcomplaining about the fact that we try to print out balance attribute of the stefansacc objectalthough we never created balance attribute for this object stefansacc account(stefansacc print_info(remember to always make sure that any attribute that your methods try to access actually exists in this caseusing constructor method is helpful in pythona constructor method is in fact an initialization method class account(object)'' class representing an account ''constructor def __init__(selfnumperson)self balance self number num self holder person methods main part of the program execution starts hereif __name__ ="__main__"annesacc account( "anne"annesacc deposit( annesacc print_info(stefansacc account( "stefan"stefansacc deposit( stefansacc print_info(in pythonconstructor methods must have the name init (note the two underscores at either side)and it must have self parameter when creating an objectsuch as in line the following happenspython creates new objectannesacc and then calls the constructor method init (selfnumpersonthe values of the parameters num and person are given when creating the object by calling the classaccount( "anne"againthe new annesacc annemarie friedrichcis lmu munchenws / |
12,378 | object is automatically assigned to the self parameterand inside the constructor methodwe can now assign the necessary attributes to the object the python statement annesacc account( "anne"triggers the following steps new object is created from the account class and assigned to the variable annesacc the constructor method of the account class is called in this stepthe newly created object is assigned to the self parameter of the constructor method so technicallypython executes account init (annesacc "anne" inside the constructor methodthe new object is initialized (the attributes are set to the given or default valuesin pythonconstructor methods do not create an object you can imagine that the creation of an object happens 'under the hoodand the constructor method then just initializes the attributes of the object (but this is rather technical detail just remember that the init (selfmethod is executed right after an object has been created class design generallywhen designing classyou have to ask yourself the following questions how can describe the state of my objectthis will result in some attributes what do know about the object before/when creating itthis goes into the constructor method what operations that change the object' attributes will be performed on the objectthese operations need to be implemented as instance methods when designing the account classthe answers to the above questions are as follows the state of an account is described by its account numberaccount holder and the current balance when creating an accounti know the new account number and the holder' name the default balance of an account is we pass the account number and the holder' name to the constructor methodand set the default balance to we will change the balance attribute of the account when withdrawing or depositing money alsoa method that prints out all information we have about the state of the account is useful annemarie friedrichcis lmu munchenws / |
12,379 | manipulate attributes only via instance methods it was said earlier that assigning value to an object' attribute like this is bad stylestefansacc balance in oopan important principle is the one of data encapsulationwhich means that the attributes of an object should be 'hiddenfrom manipulations from 'outside( from the code that uses the objectthe attributes of an object should only be modified using code that was written within the class definition this ensures that the state of the object is always valid imaginestefan' account balance is $ and he wants to withdraw $ howeverstefan' account has the restriction that it may not have negative balance assume the (humanteller at the bank forgets about this restrictionsets the balance manually to -$ and hands the cash to stefan you can imagine that this would make the branch manager of the bank quite unhappy when he realizes that stefan' account is in state that is not allowed the withdraw(selfamountmethod modifies the balance attributebut we can control this manipulation in the method for instancewe could prohibit withdrawals that would result in negative balance class account(object)'' class representing an account ''methods def withdraw(selfamount)if amount self balanceamount self balance self balance -amount return amount main part of the program if __name__ ="__main__"annesacc account( "anne"annesacc deposit( print("trying to withdraw :"cash annesacc withdraw( print("yeahi got:"cash print("trying to withdraw :"cash annesacc withdraw( print("oh noi only got:"cash annemarie friedrichcis lmu munchenws / |
12,380 | provide for changing attributes by defining setter methods sometimesan attribute has to be changed completely assumefor tax reasonsit is preferable for stefan to change the account holder to its wife because we said that assigning value to an attribute from the outside like stefansacc holder "andreais bad stylewe provide setter method for this case class account(object)'' class representing an account ''def set_holder(selfperson)self holder person main part of the program execution starts hereif __name__ ="__main__"stefansacc account( "stefan"stefansacc deposit( stefansacc set_holder("andrea"stefansacc print_info(in the above codethe setter method simply sets the object' attribute to the given value this may seem superfluous at the momentand there are actually other (saferways to do this in python (keywordpropertieshoweverfor nowwe go along with the python programming principle of trusting the code that uses your classes and stick to the following rules in order not to violate the data encapsulation paradigm assign values to attributes only via instance methods (settersor the constructor modify the values of attributes only via instance methods accessing (readingthe value of attributes like print(stefansacc balanceis okay so what good is thatfor instanceinside the setter methodswe can validate the new valueor raise an exception if the new value is not valid the new value for the account holder attribute has to be name or at least non-empty string that contains only letters and spaces we could hence write the setter method like this def set_holder(selfperson)if (not type(person=str)raise typeerror if not re match("\ +\ +)*"person strip())raise valueerror self holder person annemarie friedrichcis lmu munchenws / |
12,381 | string representations of objects oftenit is useful to have meaningful string representation of an object if we tell python to print an objectfor instance print(annesacc)python gives the cryptic answer "insteadwe would rather have string representation that really tells us what' going on with the attributes of the objectsuch as the information that the print info(selfmethod gives us in pythonwe can simply add an instance method that has the name str (self(no parameters besides self!to the class this method must return some string that describes the object we can see such method in the code listing on the following page in some casespython automatically realizes that we want string representation of an objectfor instance when calling print(annesaccor str(annesacc)it automatically calls the str (selfmethod of this object when calling print(annesacc)it prints out whatever the str (selfmethod of the annesacc object returnsstr(annesaccreturns the string that is returned by the method call annesacc str ( class accountmethods def __str__(self)res "**account info ***\nres +"account id:str(self number"\nres +"holder:self holder "\nres +"balancestr(self balance"\nreturn res if __name__ ="__main__"annesacc account( "anne"annesacc deposit( print(annesacchooks are special functions of class that are called automatically by python in some circumstances the str (selfmethod is only one example for this there is another hook method called repr (selfwhich is also supposed to return string that describes the object str (selfis supposed to return user-friendly description of the objectwhile repr (selfshould return description that is useful for developers note that print(anobjectreturns the string returned by the str (selfmethodwhile printing an object by just typing it in the interactive mode returns the string returned by repr (selfanother hook function that we have seen already is the constructor method init (selfargs))which is called when creating new object by calling class there are also hook methods that are triggered when operators are appliedfor example the operator triggers the add method of an object note that the names of hook methods usually start and end with two underscores we will learn more about hooks later annemarie friedrichcis lmu munchenws / |
12,382 | classes are objectstoo in pythonclasses are objectstoo they are created when defining class using the class statement after defining the account classexactly one class object for the account class becomes available each time we call this class ( annesacc account())we create new instance object of this class the object annesacc is automatically linked to the account class objectwe say annesacc 'is-aaccountbecause it' an instance of the account class when we try to access component (an attribute or methodof an object using the dot notation in the way objectname componentnamepython first looks in the object itself each object can be seen as its own namespace if python finds the componentname thereit is happy if it doesn'tit looks in the class object of the class from which the object was created if it doesn' find the componentname therean error occurs let' look at an example assume that the account class has three methodswithdraw(selfamount)deposit(selfamountand print info(selfwe created the object annesacc by calling the account classand then we assigned an attribute to the annesacc object by writing annesacc balance the annesacc object is linked to the class it was created fromas shown in the image on the next page when we use the dot notation in order to access an attribute or method of the annesacc objectpython starts searching for this attribute or component at the object itself for examplewhen accessing the balance attribute (print(annesacc balance))it finds the attribute right at the object and is happy theoreticallyyou can also define methods only for particular instances practicallymethods are always defined within classes we can call the methods 'on an objectusing the dot notation againlike for instance in line herepython first looks at the objectbut it doesn' have method called deposit(amountpython then checks the class from which the object was createdand finds the method there the deposit(selfamountmethod of the account class object is then called in particular waywhich we will consider using our example although the method deposit(selfamounthas two parameterswe only have to call it with one parameter (the amount of money we intend to depositwe have already learned thatt he three methods are so-called instance methodswhich means they should only be called 'on an object' in the waysomeobject method(parameters when we define an instance method (inside class)the first parameter has to be called self by convention when we call the instance methodpython automatically annemarie friedrichcis lmu munchenws / |
12,383 | assigns the object on which the method was called to this self parameter so this is what happens herein line we create the object annesacc from the account class the object annesacc is linked to the account classwhich provides the three instance methods mentioned above in line we add an attribute called balance to the object annesaccand give it value of the attribute is only available in this particular objectnot to the account class or any other objects which we might create from the account class later on in line we call an instance method of the object annesacc the object was created from the account classso we look for the method being called in this class the method was defined as deposit(selfamount)but we pass just one parameter when calling it (amountpython automatically associates the annesacc object with the parameter selfand we only need to provide the parameters from the second one in the parameter list on inside the deposit methodwe have access to the object on which it was called (annesaccvia the self variableand can modify the balance attribute of this object classes can have attributestoo we already know that classes are some kind of objectstoo instances link to the class object of the class from which they were createdso for example we can use the deposit(selfamountmethod of the account class to modify any instance created from the account class class object can also have attributeswhich we call class attributes in the following examplethe account class has class attribute called num of accountswhich records how many accounts were created so what exactly happens herein line we create the class attribute by assigning variable called num of accounts in the namespace of the account class note that the class variable has the same indent as the methods we defined within the class at the time when the class object is createdthe initial value for the class attribute is set to in the constructor methodwe modify the num of accounts class attribute recall that the init method is called each time when an instance object is created from the class each time this happenswe increment the num of accounts class attribute we access the class attribute by using the class name together with the dot notationaccount num of accounts (as shown in lines and annemarie friedrichcis lmu munchenws / |
12,384 | class account '' class representing an account '' class attributes num_of_accounts constructor def __init__(selfnumperson) self balance self number num self holder person account num_of_accounts + methods main part of the program if __name__=="__main__" print(account num_of_accounts"accounts have been created " annesacc account( "anne" annesacc deposit( stefansacc account( "stefan" print(account num_of_accounts"accounts have been created the image on the previous page shows that the num of accounts attribute resides within the account class object so farwe have seen the conceptclass objects can have attributestooand we assign them in the namespace of the class (either in the class with the correct indent or using classname attributenamehoweverwe can also access the class attributes via instance objects that were created from the classas the interactive session shows account num_of_accounts annesacc num_of_accounts stefansacc num_of_accounts the image on the previous page also explains why that is as beforepython starts searching for an attribute in the instance objectif it doesn' find itit moves on the class from which the object was created henceall of the above statements access the same attribute (the class attribute of the account classif it is changed ( by creating yet another account object)we can see the following output andreasacc account( "andrea"account num_of_accounts annesacc num_of_accounts stefansacc num_of_accounts annemarie friedrichcis lmu munchenws / |
12,385 | so farso good in the following casehoweverit gets tricky and we have to program carefully in order to avoid bugs annesacc num_of_accounts account num_of_accounts annesacc num_of_accounts stefansacc num_of_accounts in line we assign new instance attribute to the annesacc object it just happens to have the same name as the class attribute the following image shows that nowthe annesacc object has an attribute called num of accounts (this attribute happens to have the value howeverthe class attribute still resides in account class objectand has the value when trying to access the num of accounts attribute of the instance objects or the class objectwe now get different results while account num of accounts and stefansacc num of accounts still refer to the class attributeannesacc num of accounts refer to the new instance attribute of this object an easy way to avoid this pitfall is to give distinct names to your class attributes and never use the same names for instance attributes static methods belong to class so farwe have only seen instance methodswhich we define inside classbut which we can only call 'on an object' when particular instance is involved class can also have methods that do not involve particular instancesbut which are called on the class object ( see line such methods are called static methods when defining static methodwe need to write @staticmethod in the line before the def statement for the respective method @staticmethod is decorator for nowyou can imagine that it is special message you pass to pythonhere telling it that the method you are defining belongs to the class (not to particular objects created from the classthe method also does not have the self parameter like the instance methods we have seen before annemarie friedrichcis lmu munchenws / |
12,386 | class account '' class representing an account '' class attributes num_of_accounts @staticmethod def accounts_info() print(account num_of_accounts"accounts have been created " if __name__=="__main__" call static method account accounts_info(we can also call class methods on objects of the classfor instance annesacc accounts info(in this casepython calls the accounts info(method of the class from which annesacc was created it does not pass annesacc as an implicit argument as it is done in instance methods using the self parameter as you can seestatic methods don' care about particular objectsand the coding style is better if you call them on the class as in the listing above python also provides more sophisticated way to define methods that belong to classesso-called class methods these are beyond the scope of this tutorial using classes in other files usuallyyou will write your classes into various files (modules)and you want to use them in another file which contains your main application an easy way to be able to use your class is to write the class definition into file (modulewhich we call accounts pyand then have the main part of your application in another filehere called bank py the bank py file must then import your classes note that the syntax for importing your class is from modulename import classnamewhere modulename has to match the file name in which your class is defined (minus the pyand classname is the name of your class from accounts import account if __name__ ="__main__"annesacc account(annesacc balance annesacc deposit( annesacc withdraw( annesacc print_info(annemarie friedrichcis lmu munchenws / |
12,387 | composition/aggregation recall that each value in python has typee has the type float or 'pythonhas the type str (=stringif we create an objectit also has typewhich is the class from which it was created we can check the type of an object using the type function stefansacc account( "stefan" type(stefansacc the type of the stefansacc object is the class from which it was created the attributes of an object can be of any type this means that the attributes of an object can be objects themselves in factalthough we haven' told you so faranything is an object in pythonalso stringsnumberslists or dictionaries the terms composition and aggregation refer to the fact that we can compose more complex objects out of multiple objects composition implies that the owned objects only exist 'withinthe more complex object for instanceif university is closedso are all its departments aggregation implies that an object is part of more complex objectbut if the larger object is destroyedthe smaller one may still exist for instancewe can define person class that deals with information about personsand we save the information about an account holder in person object as shown in the following example if the account is closedthe person still exists (and so may its object bank might save information about former customer even after the customer closed his or her account class persondef __init__(selffla)self firstname self lastname self age def __str__(self)return "[personself firstname self lastname (str(self age")]class accountdef __init__(selfpersonnum)self holder person self num num self balance def deposit(selfamount)self balance +amount anne person("anne""friedrich" annesacc account(anne annemarie friedrichcis lmu munchenws / |
12,388 | in uml class diagramswe can show that one class has an attribute whose type is another class using line that connects the two classes the diamond symbol shows that the account class uses the person class in the case of compositionthe diamond symbol is filled (blackplease note that uml class diagrams show the class designi how objects created from this class will look like they show the attributes and methods that will be available for objects created from this class uml diagrams do not show what is going on in python internally (for this we used the diagrams with the grey boxesfor exampleinstance attributes will not be available in the class objectbut we list them in the class diagram class attributes and static methods are underlined in uml class diagrams inheritance makes programmer' life easier inheritance is central principle in oop which leverages commonalities and differences between objects which have to be dealt with in our code the big advantageas we will seeis that inheritance minimizes redundancy (we don' have to write the same code over and over againand thus also facilitates maintenance (if we need to change something in the codewe need to do it only onceif the functionality is shared by different classesthis may sound very abstractso let' have look at concrete example assume our bank offers two different kind of accountssavings accountwe record the account numberholder and balance with each account the balance has to be > we can apply an interest rate which is defined once for all savings accounts money can be deposited into the account the account statement that can be printed includes the account numberholder and balance checking accountwe record the account numberholder and balance with each account the balance has to be greater than or equal to credit range which is determined on per-customer basis for instanceif the credit range determined for anne is $ her balance may not be less than $ money can be deposited into the account the account statement that can be printed includes the account numberholder and balance usuallythe development of an application starts with description of some reallife objects (such as the accountslike above nowwe have to map these descriptions into an object-oriented design we can make the following statements about our application settingannemarie friedrichcis lmu munchenws / |
12,389 | both the savings account and the checking account are some type of account we can deposit money into either account type the account statements to be printed out are the same for the two account types the savings account and the checking account both have the following attributesaccount number account holder balance the savings accounts have an additional parameterthe interest ratebut which is the same for all savings accounts savings accounts have behavior that checking accounts don' havewe can apply the interest rate on their balances each checking account has its own particular credit range cash withdrawal works differently for the two account types in the savings accountthe balance may not be less than while for checking accountsthe balance may not be less than the credit range defined for the particular client base classes provide general functionality all of the above considerations will be reflected in our class design first of allwe will code base class which implements all the things that are shared by the two types of accountsthe attributes holdernumber and balancemethods for deposit and withdrawal as well as for printing out the state of the account the following listing shows our base classaccountwhich doesn' look much different from the previous class in factwe could instantiate objects directly from this class and use them as accounts class account '' class representing an account '' constructor def __init__(selfnumperson) self balance self number num self holder person methods def deposit(selfamount) self balance +amount def withdraw(selfamount) if amount self balance amount self balance self balance -amount return amount def __str__(self) res "**account info ***\ res +"account id:str(self number"\ res +"holder:self holder "\ res +"balancestr(self balance"\ return res annemarie friedrichcis lmu munchenws / |
12,390 | derived classes provide for special needs let' turn to the savings accounts in factthey are specialized case of the account class we have just written nextwe are going to write class called savingsaccount which extends the account classor is derived from it this basically means that all functionality that is available in the account class is also available in the savingsaccount class we tell python that the savingsaccount class is based on the account class by starting the class definition with class savingsaccount(accountwe say that derived class/subclass is based on superclass/base class this means that anything that is available in the superclass is also available in the subclass class savingsaccount(account) ''class for objects representing savings accounts shows how class can be extended '' interest_rate methods def apply_interest(self) self balance *( +savingsaccount interest_ratein our main applicationwe instantiate two savings accounts if __name__=="__main__" annesacc savingsaccount( "anne" annesacc deposit( annesacc apply_interest( print(annesacc stefansacc savingsaccount( "stefan" stefansacc deposit( stefansacc apply_interest( print(stefansaccthe image on the next page shows the class hierarchy and the objects we instantiated from it note that although the instance attributes balancenumber and holder were set in the constructor of the account classthey are attributes of the instance objects we set them as self balancenot as account balance in the constructor method when we apply any instance method on an objectthe class hierarchy is searched from bottom to the top for instancewe did not define constructor method in the savingsaccount class because the savingsaccount class is based on the account classpython continues looking for an init method at the superclass (account)finds it there and executes this method when creating new object by calling the savingsaccount class annemarie friedrichcis lmu munchenws / |
12,391 | even simplerwhen calling annesacc deposit( )python starts looking for deposit method at the annesacc objectbut doesn' find one there it then looks at the class from which the object was createdwhich happens to be savingsaccount it doesn' find the method there eitherso it continues looking for the class in the superclass of savingsaccountaccountwhere it finally finds the method the apply interest(selfmethod is found at the savingsaccount classwhich means that the search stops here and executes this method subclasses can override the behavior of their superclasses nowwe define class called checkingaccount which is also based on the account class howeverthe general withdraw(selfamountmethodwhich we defined in the account class and which does not allow withdrawal to result in negative balancedoes not apply to checking accounts recall that checking account may have negative balancebut only up to credit range which is defined on per-customer basis the following listing shows how we can redefine/replaceor (as in oop-speakoverride methods of superclass in subclass class checkingaccount(account)''class for objects representing checking accounts shows how methods can be overridden ''constructor def __init__(selfnumpersoncredit_range)print("creating checkings account"self number num self holder person self balance self credit_range credit_range methods def withdraw(selfamount)amount min(amountabs(self balance self credit_range)self balance -amount return amount annemarie friedrichcis lmu munchenws / |
12,392 | stefansacc checkingaccount( "stefan" stefansacc deposit( annesacc checkingaccount( "anne" annesacc deposit( annesacc withdraw( print(annesaccprint("trying to withdraw "cash annesacc withdraw( print("got only"cashprint(annesaccas we can seethe checkingaccount class provides constructor method init when creating an object by calling the checkingaccount classpython starts looking for constructor at this class and immediately finds one it executes the init method of the checkingaccount class and sets the four attributes of the object being created the constructor method of the superclass account is not executed in this case the checkingaccount class also overrides the withdraw(selfamountmethod of its superclass overriding method simply works by giving the exact same name to method when we call this method on the annesacc objectpython again starts looking for the method in the object and then at the classes it is linked to from bottom to top it finds the method at the checkingaccount class and executes this method methods with the same name can do different things we have defined class hierarchy by nowsavingsaccount and checkingaccount are both subclasses of account let us create two objects of these classes as follows annesacc savingsaccount( "anne"annesacc deposit( annesacc withdraw( stefansacc checkingaccount( "stefan" stefansacc deposit( stefansacc withdraw( annemarie friedrichcis lmu munchenws / |
12,393 | the image below shows the complete class hierarchy and our two account objects when creating annesaccpython looks for the constructor method in the savingsaccount classdoesn' find onand moves on to the account class it then modifies the newly created object as coded in the init method of the account class when creating the stefansacc objectpython finds constructor method in the checkingaccount class and uses this constructor directly to modify the newly created object when we apply the deposit method on either the annesacc or the stefansacc objectpython will execute the deposit method of the account classbecause it doesn' find deposit method anywhere lower in the tree when we apply the withdraw method on the stefansacc objectagainpython finds the method definition in the checkingaccount class and executes this method when we apply withdraw on annesaccpython executes the deposit method defined in the account class we just saw an example of polymorphism the word polymorphism is derived from the greek word for 'having multiple formsin this caseit means that we can call method that has the same name (for instance withdrawon several objects (here annesacc and stefansacc)and what happens depends on the inheritance hierarchy of the classes from which the objects were created the nice thing here isat the point of time when we do the withdrawalwe simply say accountobject withdraw(amountand we don' need to care about whether the accountobject is savings or checking account python knows which inheritance lines to follow and the desired behavior is produced in either case of coursewe could simply have defined the withdraw method twiceonce in the savingsaccount class and once in the checkingaccount class we defined the method in the superclass here in order to give an example for overriding methods annemarie friedrichcis lmu munchenws / |
12,394 | this might even make sense if our bank provides many more types of accounts and in most of these accountsthe withdrawal works as defined in the account class thenmost of the classes derived from account simply default to this behaviorwhile we can provide special behavior for checking accounts subclasses can extend functionality of superclasses we said that oop is great because it helps us to minimize redundancy and thus makes code maintance easier minimizing redundancy means to never write the same piece of code twice compare the constructor methods of our account class and the checkingaccount classwhich is derived from it herewe just copied and pasted parts of what is going on inside the constructor method of account into the constructor method of checkingaccount class account '' class representing an account '' constructor def __init__(selfnumperson) self balance self number num self holder person methods class checkingaccount(account) ''class for objects representing checking accounts shows how methods can be overridden '' constructor def __init__(selfnumpersoncredit_range) self number num self holder person self balance self credit_range credit_range methods as oop is greatthere is of course better way to do it we can call the constructor of superclass in the constructor of subclass in this particular caseit looks like this class checkingaccount(account) ''class for objects representing checking accounts shows how methods can be overridden '' constructor def __init__(selfnumpersoncredit_range) account __init__(selfnumperson self credit_range credit_range methods annemarie friedrichcis lmu munchenws / |
12,395 | in line we call the constructor method of the account class herewe need to explicitly pass on the self parameterbecause we are not calling the method 'on an object'but 'on the classby passing on the self parameterpython will know which object to operate on when it executes the constructor method of the account class in generalwe can call any method of superclass in this waynot only the constructor method for instancewe could implement the withdraw method in very general way in the base classand do all the consistency checking in the subclassesas shown in the following example (in this casewe're not really saving lines of codebut in more complex casethe method in the superclass might be more complexand then it really makes sense to structure your code like this class account def withdraw(selfamount) self balance -amount class savingsaccount(account) methods def withdraw(selfamount) ''balance must be '' if amount self balance amount self balance cash account withdraw(selfamount return cash class checkingaccount(account) ''class for objects representing checking accounts shows how methods can be overridden '' constructor def __init__(selfnumpersoncredit_range) account __init__(selfnumperson self credit_range credit_range methods def withdraw(selfamount) ''balance must be credit range '' amount min(amount abs(self balance self credit_range) cash account withdraw(selfamount return cash annemarie friedrichcis lmu munchenws / |
12,396 | tuesday wednesday : - : introduction to python : - : exercises object oriented programming with python : - : coffee break exercises : - : control structures coffee break : - : exercises : - : : - : lunch break numpy fast array interface to python : - : functions and modules : - : exercises : - : exercises lunch break : - : coffee break : numpy (continued : - : file / and text processing : - : exercises : - : exercises coffee break numpy (continued : - : exercises thursday : - : visualization with python : - : exercises : - : coffee break : - : scipy-package for scientific computing : - : exercises : - : lunch break : - : extensions integrating efficient routines in python : - : exercises : - : coffee break : - : mpi and python mpi py : - : exercises |
12,397 | |
12,398 | moderninterpretedobject-orientedfull featured high level programming language portable (unix/linuxmac os xwindowsopen sourceintellectual property rights held by the python software foundation python versions and is not backwards compatible with this course uses version |
12,399 | fast program development simple syntax easy to write well readable code large standard library lots of third party libraries numpyscipybiopython matplotlib |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.