Download presentation
Presentation is loading. Please wait.
1
1 Objects and classes Classes – Act as blueprints Objects are instantiated from classes – Encapsulate data: Attributes – Encapsulate function: Methods – Ideal for modeling real-world phenomena
2
2 Summary – Class header Keyword class begins definition, followed by name of class and colon ( : ) – Body of class Indented block of code – Optional documentation string Describes the class Appears immediately after class header – Constructor method __init__ Executes each time an object is created Initialize attributes of class Returns None – Object reference All methods must at least specify this one parameter ( self ) Represents object on which a method is called
3
3 An abstract game with two players Player: – Name – Overall skill (5.0 – 10.0) – Motivation flux mf (0.0 – 1.0) – Current strength: Current motivation cm : random number in [ -mf, mf ] Current strength = skill + skill * cm With motivation 1.0, current strength is 2 * skill. With motivation 0.0, current strength is skill. Motivation flux 0.0: very stable player. Motivation flux 1.0: very unstable player.
4
4 Object reference self first argument in all methods self refers to the object on which the method is called Object attribute self.skill vs. local variable skill player.py
5
5 >>> from player import Player >>> john = Player('John', 1.0, 8.0) >>> paul = Player('Paul') >>> print paul.skill 7.5 john name = ‘John’ skill = 8.0 motivation_flux = 1.0 name = ‘Paul’ skill = 7.5 motivation_flux = 0.0 paul No self argument in method calls! Python puts object reference in place of self class Player
6
6 Summary – Class header Keyword class begins definition, followed by name of class and colon ( : ) – Body of class Indented block of code – Optional documentation string Describes the class Appears immediately after class header – Constructor method __init__ Executes each time an object is created Initialize attributes of class Returns None – Object reference All methods must at least specify this one parameter Represents object of class on which a method is called Called self by convention
7
7 Remember the self. prefix when referencing object attributes >>> from player_wrong import Player >>> ringo = Player("Ringo") >>> print ringo.my_skill Traceback (most recent call last): File " ", line 1, in ? AttributeError: Player instance has no attribute ‘my_skill'
8
8 Let’s do something with our objects: method play player2.py >>> from player2 import Player >>> john = Player("John", 1.0, 8.0) >>> paul = Player("Paul") >>> john.play(paul) John (11.97) - Paul (7.50): John wins >>> john.play(paul) John (1.88) - Paul (7.50): Paul wins >>> paul.play(john) Paul (7.50) - John (3.32): Paul wins
9
9 Destructors Constructor named __init__ Destructor – Method is named __del__ – Executed automatically when object is destroyed or when no more references to object exist – Can be used for housekeeping before Python reclaims object memory
10
10 Class Attributes – One copy of attribute shared by all objects of a class – Represents “class-wide” information Property of the class, not of an object of the class – Initialized once in the class definition (not in constructor) Otherwise it would be re-initialized every time an object is created – Should be accessed through the class name or any object of the class May exist even if no objects of class exist
11
11 Adding class attribute count + destructor player3.py >>> from player3 import Player >>> paul = Player('Paul') >>> ringo = Player('Ringo') >>> del paul Player Paul deleted
12
12 Preparing to hold tournaments player4.py New object attribute wins to keep track of match results New play method which updates attribute wins
13
13 Testing.. >>> from player4 import Player >>> john = Player('John', 0.2, 8.0) >>> paul = Player('Paul') >>> john.play(paul) John defeats Paul >>> john.play(paul) John defeats Paul >>> john.play(paul) John defeats Paul >>> john.play(paul) Paul defeats John >>> print john.wins 3 >>> print paul.wins 1 >>> ^D Player Paul deleted Player John deleted threonine:~/python% NB: destructor called automatically when session ends
14
14 Now we’re ready to hold a tournament! player_game.py
15
15 Holding tournament with four players threonine:~/python% python player_game.py Player name: John John's skill (5.0-10.0): 8 John's motivation flux (0.0-1.0): 0.2 Player name: Paul Paul's skill (5.0-10.0): 7.5 Paul's motivation flux (0.0-1.0): 0 Player name: George George's skill (5.0-10.0): 7.5 George's motivation flux (0.0-1.0): 0.5 Player name: Ringo Ringo's skill (5.0-10.0): 7.5 Ringo's motivation flux (0.0-1.0): 1.0 Paul defeats John John defeats George Ringo defeats John George defeats Paul Ringo defeats Paul Ringo defeats George Ringo is the winner with 3 wins! Tournament matches Player initialization
16
16 Summary – Class header Keyword class begins definition, followed by name of class and colon ( : ) – Body of class Indented block of code – Optional documentation string Describes the class Appears immediately after class header – Constructor method __init__ Executes each time an object is created Initialize attributes of class Returns None – Object reference All methods must at least specify this one parameter ( self ) Represents object on which a method is called
17
17 Rational numbers in Python Strange rounding-off errors: Create class for representing rational numbers by storing numerator and denominator >>> 2/3.0 0.6666666666666663 >>> 2/6.0 0.3333333333333331 >>> 5/6.0 0.8333333333333337
18
18 Rational numbers rational.py Use float to make sure result of division will be a float, not a rounded down integer Object reference self first argument in all methods self refers to the object on which the method is called Initialization: Reduced form
19
19 Creating and using RationalNumber objects >>> from rational import RationalNumber >>> a = RationalNumber(3, 4) >>> b = RationalNumber(3, 6) >>> a.getValue() 0.75 >>> b.getValue() 0.5 >>> b.getNumerator() 1 >>> b.getDenominator() 2 No self argument in method calls! Python puts object reference in place of self.getDenominator( )bRationalNumber
20
20 Creating and using RationalNumber objects >>> from rational import RationalNumber >>> a = RationalNumber(3, 4) >>> b = RationalNumber(3, 6) >>> a.getValue() 0.75 >>> b.getValue() 0.5 >>> b.getNumerator() 1 >>> b.getDenominator() 2 class RationalNumber a numerator = 3 denominator = 4 numerator = 1 denominator = 2 b
21
21 Forgetting the self. prefix when referencing object attributes Initializes only local variables which go out of scope when constructor terminates!
22
22 Comparing rationals - binary search tree a elements < a elements >= a
23
23 Binary search tree a elements < b < a b <= elements < a b elements >= a elements < a
24
24 Binary search tree of rational numbers
25
25 binary_tree.py Node class from course notes Use this class to represent the search tree nodes: Each data attribute will be a RationalNumber
26
26 searchtree.py (part 1) Creating RationalNumber objects, adding them to a tree
27
27 searchtree.py (part 2) Adding a node to a binary search tree Recursive function! node rational
28
28 Testing %:~ python –i searchtree.py Numerator: 2 Denominator: 3 Numerator: 3 Denominator: 4 Numerator: 7 Denominator: 14 Numerator: >>> root.getData().getvalue() 0.666666666666663 >>> root.getRight().getData().getvalue() 0.75 >>> root.getLeft().getData().getvalue() 0.50 2/3 1/2 3/4
29
29 searchtree.py (part 3) Searching for a node Fast searching if tree is balanced
30
30 searchtreetest.py Searching for a node, demonstration Search in big tree of random rational numbers
31
31 Numerator: 2 Denominator? 3 Closest match: 433/650 Numerator: 4 Denominator? 5 Closest match: 43/54 Numerator: 1 Denominator? 2 Closest match: 370/737 Numerator: 4 Denominator? 9 Closest match: 391/878 Numerator: 10 Denominator? 1 Closest match: 994/103 Numerator: 5 Denominator? 3 Closest match: 521/313
32
32.. on to the exercises
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.