By: Chris Harvey Python Classes
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
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
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
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')
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
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)
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
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_)
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
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)