1 / 23

Python Classes

Python Classes. Nik Bournelis. In General. Classes for python are not much different than those of other languages Not much new syntax or semantics Python classes are still able to have multiple base classes Derived classes can override methods from base classes with the same name

webbp
Download Presentation

Python Classes

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

E N D

Presentation Transcript


  1. Python Classes Nik Bournelis

  2. In General • Classes for python are not much different than those of other languages • Not much new syntax or semantics • Python classes are still able to have multiple base classes • Derived classes can override methods from base classes with the same name • Member functions are virtual by default

  3. Names and Objects • Objects in python have aliasing • Have individuality • Multiple names can be bound to the same object • An object’s alias behaves like a pointer • Easier and quicker for program to pass a pointer rather than an object

  4. Scopes and Namespaces • Namespace: mapping from names to objects • Ex: functions such as abs(), global names in a module • Names within namespaces do not relate to each other • Two modules may define a function with the same name without the program becoming confused as to which to use • Attributes within namespaces can be both read-only and writable Ex: modname.the_answer = 42 • To delete attributes, use “del” del modname.the_answer • the attribute “the_answer” will be deleted from modname

  5. Namespace Lifetimes • Namespaces with built-in names is created when the program begins and is never deleted • A global namespace for a module is created when the module is read by the program interpreter, and last until the program exits • Local namespaces are created when functions run, and usually deleted when the function returns a value or raises an exception it cannot handle

  6. Scopes • A scope is a region in the code where the namespace is directly accessible • References to a name will look here for a definition of the name in the namespace • Nested scopes whose names are directly accessible: • Innermost scope (contains local names) • Scopes of any functions (contains names specific to the funtion) • Next to last scope (contains global names) • Outermost scope (contains built-in names from namespaces of python)

  7. Class Definition • Simplest form of a class - class Classname: <statement – 1> … <statement – N> • Class definitions are like function definitions • Must be executed before they have effect • Could even be placed inside an if statement or function • Usually statements inside class definitions are function definitions • Namespaces are created as a local scope when class definitions are created • If a class definition is left normally, a class object is created

  8. Class Objects • Class objects support two kinds of operations • Attribute references • Instantiation

  9. Attribute References class MyClass: """A simple example class""" i = 12345 def f(self): return 'hello world’ • MyClass.i – returns an integer • MyClass.f – returns a function object • Can also define class attributes (MyClass.i = 6420)

  10. Instantiation • Uses function notation • Act as if the class object is a parameterless function • Returns a new instance of the class x = MyClass() • creates a new instance of the MyClass class and assigns it to x • Rather than create an empty class, programmer can define __init__() method: def __init__(self): self.data = [] • Allows the programmer to define an initial state other than being empty

  11. __init__() can also have parameters if the programmer would like for easier use >>> class Complex: ... def __init__(self, realpart, imagpart): ... self.r = realpart ... self.i = imagpart ... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)

  12. Method Objects • Method objects are objects that have been applied to a function, then stored as an object xf = x.f while True: print xf() • The object is passed as the first argument of the function when there are no parameters • So in this case, x.f() is equivalent to MyClass.f(x)

  13. Inheritance • Basic syntax for a derived class definition: class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N> • As stated before, all methods are virtual by default • If a method in DerivedClassName above has the same name and parameters as BaseClassName, the method in the derived class will be implemented when its called

  14. Multiple Inheritance class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N> • Program searches through each base class left to right when searching for attributes • If Base1 is a derived class, the program will go through its base classes recursively to complete the search

  15. Private Variables • Programmers that use python typically use an underscore as a prefix to private variables Ex: __color • Name mangling – a method used by programmers to avoid name clashes by subclasses and their base classes Syntax: _classname__color

  16. A Useful Data Type • Similar to “struct” type in C or C++ • Binds together attributes class Employee: pass john = Employee() # Create an empty employee record # Fill the fields of the record john.name = 'John Doe' john.dept = 'computer lab' john.salary = 1000

  17. Exceptions • In python, exceptions are defined in classes • Two new ways for “raise” statement to be used: raise Class, instance #’instance’ must be an instance of Class or a class derived # from it raise instance #shorthand for writing ‘instance.__class__, instance’

  18. ExceptionExample • Will output B, C, D • If the excepts were reversed, the output would be B, B, B • B is in class B (first B), • class C is derived from class B (second B), • class D is derived from class C, which is derived from class B, and how the third B is obtained class B: pass class C(B): pass class D(C): pass for c in [B, C, D]: try: raise c() except D: print "D" except C: print "C" except B: print "B"

  19. Iterators in Python • Serve the same function as we have learned in C++ • The programmer must define an __iter__() method that returns an object with the next() method

  20. Iterator Example >>> s = 'abc‘ >>> it = iter(s) >>> it <iterator object at 0x00A1DB50> >>> it.next() 'a' >>> it.next() 'b' >>> it.next() 'c' >>> it.next()

  21. Generators • Generators are simple, yet powerful tools for creating iterators in python • Written as regular function, but use ‘yield’ to return data • Resumes wherever it left off when next() is called • Can remember position and data values it was at when last executed def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] >>> for char in reverse('golf'): ... print char ... f l o g

  22. More Generators • Generators automatically create __iter__() and next() methods • Which is why they are considered so compact and simple • Local variable and execution states automatically saved between calls • Don’t need to create variables to store this information • Also raises StopIteration automatically when the generator terminates • Using generators, programmers can use iterators with as much ease as creating a new function

  23. Sources • http://docs.python.org/tutorial/classes.html

More Related