Text
stringlengths
1
9.41k
In the above program, the constructor takes two values, a and b, and assigns the class variables a and b to those values. - The first argument to every method in your class is a special variable called self.
Every time your class refers to one of its variables or methods, it must precede them by self.
The purpose of self is to distinguish your class’s variables and methods from other variables and functions in the program. - To create a new object from the class, you call the class name along with any values that you want to send to the constructor.
You will usually want to assign it to a variable name.
This is what the line e=Example(8,6) does. - To use the object’s methods, use the dot operator, as in e.addmod(). **A more practical example** Here is a class called Analyzer that performs some simple analysis on a string.
There are methods to return how many words are in the string, how many are of a given length, and how many start with a given string. |imple example Here is a simple example to demonstrate what a class looks like.
It does not anything interesting.|Col2| |---|---| ||| |class Example: def __init__(self, a, b): self.a = a self.b = b def add(self): return self.a + self.b e = Example(8, 6) print(e.add())|| |more practical example Here is a class called Analyzer that performs some simple analysis a string.
There are methods to return how many words are in the string, how many are of a en length, and how many start with a given string.|Col2| |---|---| ||| |from string import punctuation class Analyzer: def __init__(self, s): for c in punctuation: s = s.replace(c,'')|| ----- _14.2.
CREATING YOUR OWN CLASSES_ 131 s = s.lower() self.words = s.split() **def number_of_words(self):** **return len(self.words)** **def starts_with(self, s):** **return len([w for w in self.words if w[:len(s)]==s])** **def number_with_length(self, n):** **return len([w for w in self.words if len(w)==n])** s = 'This...
It is also good just for organizing things.
If all our program is doing is just analyzing some strings, then there’s not too much of a point of writing a class, but if this were to be a part of a larger program, then using a class provides a nice way to separate the Analyzer code from the rest of the code.
It also means that if we were to change the internals of the Analyzer class, the rest of the program would not be affected as long as the interface, the way the rest of the program interacts with the class, does not change.
Also, the Analyzer class can be imported as-is in other programs. - The following line accesses a class variable: **print(analyzer.words)** You can also change class variables.
This is not always a good thing. In some cases this is convenient, but you have to be careful with it.
Indiscriminate use of class variables goes against the idea of encapsulation and can lead to programming errors that are hard to fix.
Some other object-oriented programming languages have a notion of public and private variables, public variables being those that anyone can access and change, and private variables being only accessible to methods within the class.
In Python all variables are public, and it is up to the programmer to be responsible with them.
There is a convention where you name those variables that you want to be private with a starting underscore, like _var1.
This serves to let others know that this variable is internal to the class and shouldn’t be touched. ----- 132 _CHAPTER 14.
OBJECT-ORIENTED PROGRAMMING_ ###### 14.3 Inheritance In object-oriented programming there is a concept called inheritance where you can create a class that builds off of another class.
When you do this, the new class gets all of the variables and methods of the class it is inheriting from (called the base class).
It can then define additional variables and methods that are not present in the base class, and it can also override some of the methods of the base class.
That is, it can rewrite them to suit its own purposes.
Here is a simple example: **class Parent:** **def __init__(self, a):** self.a = a **def method1(self):** **return self.a*2** **def method2(self):** **return self.a+'!!!'** **class Child(Parent):** **def __init__(self, a, b):** self.a = a self.b = b **def method1(self):** **return self.a*7** **def method3(s...
Child method 3: hibye We see in the example above that the child has overridden the parent’s method1, causing it to now repeat the string seven times.
The child has inherited the parent’s method2, so it can use it without having to define it.
The child also adds some features to the parent class, namely a new variable b and a new method, method3. A note about syntax: when inheriting from a class, you indicate the parent class in parentheses in the class statement. |object-oriented programming there is a concept called inheritance where you can create a cl...
When you do this, the new class gets all of the variables and thods of the class it is inheriting from (called the base class).
It can then define additional variables d methods that are not present in the base class, and it can also override some of the methods of base class.
That is, it can rewrite them to suit its own purposes.
Here is a simple example:|Col2| |---|---| ||| |class Parent: def __init__(self, a): self.a = a def method1(self): return self.a*2 def method2(self): return self.a+'!!!' class Child(Parent): def __init__(self, a, b): self.a = a self.b = b def method1(self): return self.a*7 def method3(self): return self.a + self.b p = P...
A PLAYING-CARD EXAMPLE_ 133 If the child class adds some new variables, it can call the parent class’s constructor as demonstrated below.
Another use is if the child class just wants to add on to one of the parent’s methods.
In the example below, the child’s print_var method calls the parent’s print_var method and adds an additional line. **class Parent:** **def __init__(self, a):** self.a = a **def print_var(self):** **print("The value of this class's variables are:")** **print(self.a)** **class Child(Parent):** **def __init__(self...
We will create a simple hi-lo card game where the user is given a card and they have to say if the next card will be higher or lower than it.
This game could easily be done without classes, but we will create classes to represent a card and a deck of cards, and these classes can be reused in other card games. We start with a class for a playing card.
The data associated with a card consists of its value (2 through 14) and its suit. The Card class below has only one method, __str__.
This is a special method that, among other things, tells the print function how to print a Card object. |he child class adds some new variables, it can call the parent class’s constructor as demonstrated ow.
Another use is if the child class just wants to add on to one of the parent’s methods.
In the mple below, the child’s print_var method calls the parent’s print_var method and adds an ditional line.|Col2| |---|---| ||| |class Parent: def __init__(self, a): self.a = a def print_var(self): print("The value of this class's variables are:") print(self.a) class Child(Parent): def __init__(self, a, b): Parent._...
OBJECT-ORIENTED PROGRAMMING_ **return '{} of {}'.format(self.value, self.suit)** **else:** **return '{} of {}'.format(names[self.value-11], self.suit)** Next we have a class to represent a group of cards.
Its data consists of a list of Card objects.
It has a number of methods: nextCard which removes the first card from the list and returns it; hasCard which returns True or False depending on if there are any cards left in the list; size, which returns how many cards are in the list; and shuffle, which shuffles the list. **import random** **class Card_group:** *...
The idea here is that Card_group represents an arbitrary group of cards, and Standard_deck represents a specific group of cards, namely the standard deck of 52 cards used in most card games. **class Standard_deck(Card_group):** **def __init__(self):** self.cards = [] **for s in ['Hearts', 'Diamonds', 'Clubs', 'Spade...
If we wanted to create a new class for a Pinochle game or some other game that doesn’t use the standard deck, then we would have to copy and paste the standard deck code and modify lots of things.
By doing things more generally, like we’ve done here, each time we want a new type of deck, we can build off of (inherit from) what is in Card_group.
For instance, a Pinochle deck class would look like this: **class Pinochle_deck(Card_group):** **def __init__(self):** self.cards = [] **for s in ['Hearts', 'Diamonds', 'Clubs', 'Spades']*2:** |sCard which returns True or False depending on if there are any cards left in the list; size, ich returns how many cards a...
The idea here is that rd_group represents an arbitrary group of cards, and Standard_deck represents a specific up of cards, namely the standard deck of 52 cards used in most card games.|Col2| |---|---| ||| |class Standard_deck(Card_group): def __init__(self): self.cards = [] for s in ['Hearts', 'Diamonds', 'Clubs', 'Sp...
If we wanted to create a new class for a Pinochle game or some er game that doesn’t use the standard deck, then we would have to copy and paste the standard k code and modify lots of things.
By doing things more generally, like we’ve done here, each e we want a new type of deck, we can build off of (inherit from) what is in Card_group.
For tance, a Pinochle deck class would look like this:|Col2| |---|---| ||| |class Pinochle_deck(Card_group): def __init__(self): self.cards = [] for s in ['Hearts', 'Diamonds', 'Clubs', 'Spades']*2:|| ----- _14.4.
A PLAYING-CARD EXAMPLE_ 135 **for v in range(9,15):** self.cards.append(Card(v, s)) A Pinochle deck has only nines, tens, jacks, queens, kings, and aces.
There are two copies of each card in each suit. Here is the hi-low program that uses the classes we have developed here.
One way to think of what we have done with the classes is that we have built up a miniature card programming language, where we can think about how a card game works and not have to worry about exactly how cards are shuffled or dealt or whatever, since that is wrapped up into the classes.
For the hi-low game, we get a new deck of cards, shuffle it, and then deal out the cards one at a time. When we run out of cards, we get a new deck and shuffle it.
A nice feature of this game is that it deals out all 52 cards of a deck, so a player can use their memory to help them play the game. |ere we can think about how a card game works and not have to worry about exactly how cards shuffled or dealt or whatever, since that is wrapped up into the classes.
For the hi-low game, get a new deck of cards, shuffle it, and then deal out the cards one at a time. When we run out ards, we get a new deck and shuffle it.
A nice feature of this game is that it deals out all 52 cards a deck, so a player can use their memory to help them play the game.|Col2| |---|---| ||| |deck = Standard_deck() deck.shuffle() new_card = deck.nextCard() print('\n', new_card) choice = input("Higher (h) or lower (l): ") streak = 0 while (choice=='h' or choi...
That's", streak, "in a row!") elif (choice.lower()=='h' and new_card.value<old_card.value or\ choice.lower()=='l' and new_card.value>old_card.value): streak = 0 print('Wrong.') else: print('Push.') print('\n', new_card) choice = input("Higher (h) or lower (l): ")|| ----- 136 _CHAPTER 14.
OBJECT-ORIENTED PROGRAMMING_ ###### Higher (h) or lower (l): h Right! That's 2 in a row! 14.5 A Tic-tac-toe example In this section we create an object-oriented Tic-tac-toe game.
We use a class to wrap up the logic of the game. The class contains two variables, an integer representing the current player, and a 3 3 _×_ list representing the board.
The board variable consists of zeros, ones, and twos. Zeros represent an open spot, while ones and twos represent spots marked by players 1 and 2, respectively.
There are four methods: - get_open_spots — returns a list of the places on the board that have not yet been marked by players - is_valid_move — takes a row and a column representing a potential move, and returns **True if move is allowed and False otherwise** - make_move — takes a row and a column representin...
A TIC-TAC-TOE EXAMPLE_ 137 **for c in range(3):** **if self.B[0][c]==self.B[1][c]==self.B[2][c]!=0:** **return self.B[0][c]** **for r in range(3):** **if self.B[r][0]==self.B[r][1]==self.B[r][2]!=0:** **return self.B[r][0]** **if self.B[0][0]==self.B[1][1]==self.B[2][2]!=0:** **return self.B[0][0]** **if self....
There is nothing in the class that is specific to the user interface. Below we have a text-based interface using print and input statements.
If we decide to use a graphical interface, we can use the Tic_tac_toe class without having to change anything about it. Note that the get_open_spots method is not used by this program.
It is useful, however, if you want to implement a computer player.
A simple computer player would call that method and use random.choice method to choose a random element from the returned list of spots. **def print_board():** chars = ['-', 'X', 'O'] **for r in range(3):** **for c in range(3):** **print(chars[game.B[r][c]], end=' ')** **print()** game = tic_tac_toe() **while gam...
Below we have a text-based interface using print and input statements. If we decide to a graphical interface, we can use the Tic_tac_toe class without having to change anything ut it.
Note that the get_open_spots method is not used by this program. It is useful, however, ou want to implement a computer player.
A simple computer player would call that method d use random.choice method to choose a random element from the returned list of spots.|Col2| |---|---| ||| |def print_board(): chars = ['-', 'X', 'O'] for r in range(3): for c in range(3): print(chars[game.B[r][c]], end=' ') print() game = tic_tac_toe() while game.check_f...
OBJECT-ORIENTED PROGRAMMING_ ###### Enter spot, player 2: 0,2 - - O - X - - - Enter spot, player 1: 14.6 Further topics - Special methods — We have seen two special methods already, the constructor __init__ and the method __str__ which determines what your objects look like when printed.
There are many others. For instance, there is __add__ that allows your object to use the + operator. There are special methods for all the Python operators.
There is also a method called __len__ which allows your object to work with the built in len function.
There is even a special method, __getitem__ that lets your program work with list and string brackets []. - Copying objects — If you want to make a copy of an object x, it is not enough to do the following: x_copy = x The reason is discussed in Section 19.1.
Instead, do the following: **from copy import copy** x_copy = copy(x) - Keeping your code in multiple files — If you want to reuse a class in several programs, you do not have to copy and paste the code into each.
You can save it in a file and use an import statement to import it into your programs.
The file will need to be somewhere your program can find it, like in the same directory. **from analyzer import Analyzer** ###### 14.7 Exercises 1.
Write a class called Investment with fields called principal and interest. The constructor should set the values of those fields.
There should be a method called value_after that returns the value of the investment after n years. The formula for this is p(1 + i)[n], where p is the principal, and i is the interest rate.
It should also use the special method __str__ so that printing the object will result in something like below: Principal - $1000.00, Interest rate - 5.12% 2. Write a class called Product.
The class should have fields called name, amount, and price, holding the product’s name, the number of items of that product in stock, and the regular price of the product.
There should be a method get_price that receives the number of items to be bought and returns a the cost of buying that many items, where the regular price ----- _14.7.
EXERCISES_ 139 is charged for orders of less than 10 items, a 10% discount is applied for orders of between 10 and 99 items, and a 20% discount is applied for orders of 100 or more items.
There should also be a method called make_purchase that receives the number of items to be bought and decreases amount by that much. 3. Write a class called Password_manager.
The class should have a list called old_passwords that holds all of the user’s past passwords. The last item of the list is the user’s current password.
There should be a method called get_password that returns the current password and a method called set_password that sets the user’s password.
The set_password method should only change the password if the attempted password is different from all the user’s past passwords.
Finally, create a method called is_correct that receives a string and returns a boolean True or False depending on whether the string is equal to the current password or not. 4.
Write a class called Time whose only field is a time in seconds.
It should have a method called convert_to_minutes that returns a string of minutes and seconds formatted as in the following example: if seconds is 230, the method should return '5:50'.
It should also have a method called convert_to_hours that returns a string of hours, minutes, and seconds formatted analogously to the previous method. 5. Write a class called Wordplay.
It should have a field that holds a list of words. The user of the class should pass the list of words they want to use to the class.
There should be the following methods: - words_with_length(length) — returns a list of all the words of length length - starts_with(s) — returns a list of all the words that start with s - ends_with(s) — returns a list of all the words that end with s - palindromes() — returns a list of all the pali...
Write a class called Converter. The user will pass a length and a unit when declaring an object from the class—for example, c = Converter(9,'inches').
The possible units are inches, feet, yards, miles, kilometers, meters, centimeters, and millimeters. For each of these units there should be a method that returns the length converted into those units.
For example, using the Converter object created above, the user could call c.feet() and should get 0.75 as the result. 7.
Use the Standard_deck class of this section to create a simplified version of the game War. In this game, there are two players. Each starts with half of a deck.
The players each deal the top card from their decks and whoever has the higher card wins the other player’s cards and adds them to the bottom of his deck.
If there is a tie, the two cards are eliminated from play (this differs from the actual game, but is simpler to program). The game ends when one player runs out of cards. ----- 140 _CHAPTER 14.