Presentation is loading. Please wait.

Presentation is loading. Please wait.

Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.

Similar presentations


Presentation on theme: "Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are."— Presentation transcript:

1 Rajkumar Jayachandran

2  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  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  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  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  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  Simplest form of a class - class Classname: …  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 support two kinds of operations  Attribute references  Instantiation

9 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  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 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  Basic syntax for a derived class definition: class DerivedClassName(BaseClassName):...  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 class DerivedClassName(Base1, Base2, Base3):...  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  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  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  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

18 >>> s = 'abc‘ >>> it = iter(s) >>> it >>> it.next() 'a' >>> it.next() 'b' >>> it.next() 'c' >>> it.next()

19  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

20  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

21  http://docs.python.org/tutorial/classes.html

22

23 The two types of errors  Syntax Errors -These errors are obtained when compiling. -When the error is obtained, the program will point to the line and the part of the code where it got the error. -Python basically does not know the format of the code you put in.  Exceptions -These errors happen upon execution of the code. -There are many types, but the type and line will be displayed. -Most of them are not handled by programs

24 >>> while True print 'Hello world' File " ", line 1, in ? while True print 'Hello world' ^ SyntaxError: invalid syntax This is an example of a Python syntax error >>> 10 * (1/0) Traceback (most recent call last): File " ", line 1, in ? ZeroDivisionError: integer division or modulo by zero >>> 4 + spam*3 Traceback (most recent call last): File " ", line 1, in ? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File " ", line 1, in ? TypeError: cannot concatenate 'str' and 'int' objects 3 examples of Python exceptions

25 Handling exceptions with Try  When try is executed, it runs the code under it  If there happens to be an error, it stops the code and goes to an except of matching type  If no except of matching type can be found, then it gives an error like that of previous example.  The except clauses can hold more then 1 type  Only the first except clause will respond to the error.  Except clauses can not have any type in them, but this is not recommended.  Try can call functions to check.

26 >>> while True:... try:... x = int(raw_input("Please enter a number: "))... break... except ValueError:... print "Oops! That was no valid number. Try again..."... Example of using try except (RuntimeError, TypeError, NameError):... pass Example of multiple except uses

27 Using else  The else clause follows all except clauses  If the except clause is not executed, the else clause is.  Putting code into an else instead of putting it outside of a try statement can protect it from other exceptions

28 for arg in sys.argv[1:]: try: f = open(arg, 'r') except IOError: print 'cannot open', arg else: print arg, 'has', len(f.readlines()), 'lines' f.close() Example of using else statement

29 Exceptions may have variables  The exception itself can have variables bound to the exception instance.  The variables will be stored in instance.args.

30 >>> try:... raise Exception('spam', 'eggs')... except Exception as inst:... print type(inst) # the exception instance... print inst.args # arguments stored in.args... print inst # __str__ allows args to printed directly... x, y = inst # __getitem__ allows args to be unpacked directly... print 'x =', x... print 'y =', y... ('spam', 'eggs') x = spam y = eggs Example of what Exceptions can hold

31 Raising Exceptions  Using the raise statement, you can give yourself an error!  The type of error can be specified.  The arguments inside the error can describe the error.  If you do not intend to handle it, put it inside of try code.

32 >>> raise NameError('HiThere') Traceback (most recent call last): File " ", line 1, in ? NameError: HiThere Example of using raise >>> try:... raise NameError('HiThere')... except NameError:... print 'An exception flew by!‘... Raise... An exception flew by! Traceback (most recent call last): File " ", line 2, in ? NameError: HiThere Using raise and taking care of it

33 Using finally and with for cleanup  Finally is put after everything else after the try statement.  It always runs no matter what, and is good for closing anything open at the end.  With is used with files so that they can clean up themselves.

34 Example showing finally always being printed out >>> def divide(x, y):... try:... result = x / y... except ZeroDivisionError:... print "division by zero!"... else:... print "result is", result... finally:... print "executing finally clause"... >>> divide(2, 1) result is 2 executing finally clause >>> divide(2, 0) division by zero! executing finally clause >>> divide("2", "1") executing finally clause Traceback (most recent call last): File " ", line 1, in ? File " ", line 3, in divide TypeError: unsupported operand type(s) for /: 'str' and 'str'

35 with open("myfile.txt") as f: for line in f: print line Example showing proper usage of with, using with a file (yes, it gets its own slide)

36 User-defined Exceptions  It is possible to create your own exceptions.  Usually in some form they should be derived from the Exception class.  Usually also create a base class, and subclass for certain examples  Useful for getting information you want about an error.


Download ppt "Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are."

Similar presentations


Ads by Google