Download presentation
Presentation is loading. Please wait.
Published byDeirdre Whitehead Modified over 9 years ago
1
By: Chris Harvey Python Classes
2
Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes NameObject a5 b8 c13 NameObject x8 fibonaccifunction result21 NameObject absfunction rangefunction True1
3
Scopes Region of code with access to a specific namespace At any point, several scopes can be accessed The most local scope is accessed first NameObject a5 b8 c13 NameObject x8 fibonaccifunction result21 NameObject absfunction rangefunction True1
4
Class Definition Syntax Definition formed by a block of statements A new namespace is created during class definition A class must be defined before usage class Person: name = 'John Smith' age = 20 def SayName(self): print(self.name) def HowOld(self): return self.age
5
Class Objects Class definition itself has attributes Class definition can be instantiated Initialization methods can be added to class definitions Person.name #Alice person = Person() def __init__(self, newName): self.name = newName person = Person('Bob')
6
Instance Objects All attributes of class object exist on instance Instance can have attributes that are different from the class definition instance.tempMember = 5 print(instance.tempMember) del instance.tempMember
7
Method Objects Methods can be referred to by a name and called later When a method is called the object it is called on is passed as first argument By convention, the calling object argument is named self speak = person.SayName() speak() def SayName(self): print(self.name)
8
Inheritance A class can inherit the attribute of another class or classes A name is matched to the first base class found with depth-first, then left-to- right Types can be checked using isinstance(object,type) and issubclass(type,baseType) class Animal: #definition pass class Dog(Animal): #definition pass class Bird: #definition pass class FlyingDog(Dog,Bird): #definition pass
9
Private Variables No such thing as truly private variables By convention, an underscore denotes a private member Two underscores prefixed and up to one suffixed indicates name mangling class Person: name = 'Alice' age = 20 __secret_ = 'A private variable' print(Person._Person__secret_)
10
Iterators Classes that represent collections can offer iterators Special __iter__ and __next__ methods must be created for traversing collection Next() raises a StopIteration exception when no more elements exist def __iter__(self): return iterationObject def __next__(self): if(lastElement): raise StopIteration else: return nextElement
11
Generators Creation of iterators can be simplified Use keyword yield to designate elements of collection All iterator functionality created automatically def Squares(n): for i in range(n): yield i*i for s in Squares(3): print(s)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.