Presentation is loading. Please wait.

Presentation is loading. Please wait.

P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.

Similar presentations


Presentation on theme: "P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that."— Presentation transcript:

1 P YTHON ’ S C LASSES Ian Wynyard

2 I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that can be executed by invoking the class in a main method. An object constructed by a class is called an instance of that class Methods can be invoked upon instances of their associated class

3 P REDEFINED C LASS A TTRIBUTES AttributeTypeRead/Writ e Description __dict__dictionaryR/WClass name space __name__stringR/OName of the class __bases__tuple of classesR/OClass inheritance __doc__string OR noneR/WDocumentation string __module__StringR/WDefining module All classes in python have these 5 attributes Python supports class inheritance Python can have private class variables like Java Python handles objects with individuality with name spaces mapping class names to objects within a shared scope Multiple names can identify the same object (this is part of modules)

4 S COPES AND N AMESPACES – T UTORIAL E X. def scope_test(): def do_local(): // Default scope spam = "local spam“ def do_nonlocal(): nonlocal spam spam = "nonlocal spam“ def do_global(): global spam spam = "global spam“ spam = "test spam“ do_local() print("After local assignment:", spam) do_nonlocal() print("After nonlocal assignment:", spam) do_global() print("After global assignment:", spam) scope_test() print("In global scope:", spam)

5 D EFINING A C LASS Classes are defined in the following format: class ClassName: “Here is an explanation of the class” pass In Python the convention is the capitalize the name of the class It is also conventional to provide a brief explanation of the class The pass statement tells the interpreter to do nothing and proceed. It is removed when arguments are entered

6 I NSTANCE C ONSTRUCTION Instances are constructed in the following format: class Dog: “Is Wolfie ok? Wolfie is fine dear.” pass Then an instance is constructed by calling the class object: Max = Dog() An instance of the class Dog has been constructed. The name of the instance is Max. To access the member of an instance of a class write.

7 M ETHODS Instances are constructed in the following format: class WinkWink: def NudgeNudge (self, x): self.x = x def SayNoMore(self): print self.x pass A method is a function within a class. This example has 2. In this example nothing would happen until an instance of WinkWink was declared and SayNoMore() was invoked

8 I NVOKING M ETHODS Methods are invoked with the following declaration: KnowWhatIMean= WinkWink() KnowWhatIMean.NudgeNudge(“Wife”) KnowWhatIMean.SayNoMore() This will output Wife You can also call a method on an arbitrary object like this: WinkWink.NudgeNudge(f, ‘Wife”) WinkWink.SayNoMore(f)

9 D YNAMIC C LASS S TRUCTURE The members of a Python class can change during runtime This is different from C and Java We can delete members inruntime and return associated errors KnowWhatIMean= WinkWink() KnowWhatIMean.NudgeNudge(“Wife”) del KnowWhatIMean.x KnowWhatIMean.SayNoMore() This will output return the following error Traceback (most recent call last): File " ", line 1, in ? File " ", line 5, in bar AttributeError: WinkWink instance has no attribute 'x'

10 D YNAMIC C LASS S TRUCTURE – C ONT. The definition of a Python class can change during execution Parrot.dead = 10 NorwegianBlue = Parrot() NorwegianBlue.dead Output:10 Here we created an arbitrary value “dead” and then added it to a new member Norwegian Blue

11 C LASS D ICTIONARIES Viewing dictionaries: vars(Parrot) Output: {‘dead’: 10, “pining”:, '__module__': '__main__', '__doc__': None} These are the members of the Parrot class definition. If values are then assigned to members of the class, then the dictionary for the member changes, not the class.

12 C HANGING I NSTANCE D ICTIONARIES Let’s change something NorwegianBlue.pining vars(NorwegianBlue) {‘x’: 6} This shows the dictionary for NorwegianBlue NorwegianBlue.y = 18 vars(NorwegianBlue) {‘y’: 18, ‘x’: 6} The most recent change appears first The class dictionary doesn’t change in this case

13 C HANGING C LASS D ICTIONARIES Let’s change something else NorwegianBlue.__dict__ {‘y’: 18, ‘x’: 6} This shows the members dictionary for the class Parrot relative to NorwegianBlue NorwegianBlue.__dict__[‘z’] = 8 NorwegianBlue.z Output: 8 This let us alter and insert a new key-value pair into NorwegianBlue.__dict__. This is the same effect as changing the members of NorwegianBlue

14 N EW S TYLE C LASSES Introduced in Python 2.2 A class that has a built-in as its base Old classes were of the type instance New style classes return the same thing as x.__class__ as their type Old classes are not in Python 3, only new style Old class OldSchool: def __init__(self): Pass New class NewSchool(object): def __init__(self): Pass

15 N EW S TYLE C LASSES – D IFFERENCES Properties can be set with the @property decorator class OldSchool: def __init__(self): self.__frank = “The Tank” @property def frank(self): return self.__frank @frank.setter def frank(self, frank): self.__frank = frank Static methods can be declared with the @staticmethod decorator class StaticIAmBatman: @staticmethod def DarkKnight(): print “My parents are dead!”

16 THE END!!!!! Spam Spam Spam Spam Spam Spam………


Download ppt "P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that."

Similar presentations


Ads by Google