diff --git a/Examples/example_10_inheritance.py b/Examples/example_10_inheritance.py index 99c91cf..1831e18 100644 --- a/Examples/example_10_inheritance.py +++ b/Examples/example_10_inheritance.py @@ -3,10 +3,10 @@ class Shape(object): def area(self): - raise NotImplemented + raise NotImplementedError() def circumference(self): - raise NotImplemented + raise NotImplementedError() def __str__(self): return type(self).__name__ diff --git a/Examples/example_13_dataclasses.py b/Examples/example_13_dataclasses.py new file mode 100644 index 0000000..9745b45 --- /dev/null +++ b/Examples/example_13_dataclasses.py @@ -0,0 +1,24 @@ +from dataclasses import dataclass +from example_5_methods import Condition + + +@dataclass +class Bike: + description: str + condition: Condition + sale_price: int + cost: int = 0 + + +if __name__ == '__main__': + bike_1 = Bike("Red Raleigh cruiser", Condition.GOOD, 650, 50) + bike_2 = Bike("Red Raleigh cruiser", Condition.GOOD, 650) + + print(bike_1) + print(bike_2) + print([bike_1, bike_2]) + print(bike_1 == bike_2) + + bike_2.cost = 50 + print(bike_1 == bike_2) + diff --git a/Examples/example_14_mixins.py b/Examples/example_14_mixins.py new file mode 100644 index 0000000..8d9ec8b --- /dev/null +++ b/Examples/example_14_mixins.py @@ -0,0 +1,32 @@ +""" +Scratch file for testing concepts +""" +class AsDictMixin: + def as_dict(self): + dict_ = {} + vars_ = vars(self) + for name, value in vars_.items(): + if not name.startswith('_'): + dict_[name] = value + return dict_ + + +class Bike(AsDictMixin): + def __init__(self): + self.a = 1 + self.b = 2 + self._c = 3 + + +class User(AsDictMixin): + def __init__(self): + self.d = 1 + self.e = 2 + self._f = 3 + + +b = Bike() +print(b.as_dict()) + +u = User() +print(u.as_dict()) \ No newline at end of file diff --git a/Examples/example_1_bike_without_classes.py b/Examples/example_1_bike_without_classes.py index d1b9fe0..45f5d1c 100644 --- a/Examples/example_1_bike_without_classes.py +++ b/Examples/example_1_bike_without_classes.py @@ -22,17 +22,18 @@ def sell(bike, sold_for=None): return profit -bike1 = create_bike('Univega Alpina, orange', cost=100, sale_price=500, condition=0.5) -# bike1 = { -# 'cost': 100, -# 'condition': 0.5, -# 'description': 'Univega Alpina, orange', -# 'sale_price': 500, -# 'sold': False, -# } - -update_sale_price(bike1, 350) -# bike1['sale_price'] = 350.00 - -print(sell(bike1)) -# bike1['sold'] = True +if __name__ == '__main__': + bike1 = create_bike('Univega Alpina, orange', cost=100, sale_price=500, condition=0.5) + # bike1 = { + # 'cost': 100, + # 'condition': 0.5, + # 'description': 'Univega Alpina, orange', + # 'sale_price': 500, + # 'sold': False, + # } + + update_sale_price(bike1, 350) + # bike1['sale_price'] = 350.00 + + print(sell(bike1)) + # bike1['sold'] = True diff --git a/Examples/example_2_using_classes.py b/Examples/example_2_using_classes.py index 9d37f2e..a9a704b 100644 --- a/Examples/example_2_using_classes.py +++ b/Examples/example_2_using_classes.py @@ -1,11 +1,11 @@ -from Examples.example_5_methods import Bike, Condition +from example_5_methods import Bike, Condition -my_bike = Bike(description='Univega Alpina, orange', +my_bike = Bike('Univega Alpina, orange', condition=Condition.OKAY, sale_price=500, cost=100) -my_bike.service(spent=30, sale_price=600) # cost=$130, sale_price=$600 +my_bike.service(cost=30, new_sale_price=600) # cost=$130, sale_price=$600 print(my_bike.sale_price) # 600 diff --git a/Examples/example_5_methods.py b/Examples/example_5_methods.py index 35a1b43..1b4ce24 100644 --- a/Examples/example_5_methods.py +++ b/Examples/example_5_methods.py @@ -43,7 +43,7 @@ def service(self, cost, new_sale_price=None, new_condition=None): if __name__ == '__main__': - my_bike = Bike("Red Releigh cruiser", Condition.GOOD, 450, 50) + my_bike = Bike("Red Raleigh cruiser", Condition.GOOD, 450, 50) print(my_bike) my_bike.update_sale_price(400) @@ -53,5 +53,3 @@ def service(self, cost, new_sale_price=None, new_condition=None): print(profit) my_bike.update_sale_price(1000) - my_bike.hello = 'world' - 'world'.hi = 'hi' diff --git a/Examples/example_6_dunder_methods.py b/Examples/example_6_dunder_methods.py index bfbf812..d8f7a8b 100644 --- a/Examples/example_6_dunder_methods.py +++ b/Examples/example_6_dunder_methods.py @@ -2,10 +2,14 @@ class Condition(Enum): - NEW = 1 - GOOD = 0.8 - OKAY = 0.5 - BAD = 0.2 + NEW = 0 + GOOD = 1 + OKAY = 2 + BAD = 3 + + +class MethodNotAllowed(Exception): + pass class Bike(object): @@ -23,7 +27,7 @@ def __del__(self): def update_sale_price(self, sale_price): if self.sold: - return Exception('Action not allowed. Bike has already been sold') + raise MethodNotAllowed('Action not allowed. Bike has already been sold') self.sale_price = sale_price def sell(self): @@ -45,8 +49,7 @@ def service(self, spent, sale_price=None, condition=None): self.condition = condition def __repr__(self): - sold_or_price = "sold" if self.sold else f"${self.sale_price}" - return f'Bike: {self.description} ({sold_or_price})' + return f"Bike({repr(self.description)}, {self.condition}, {self.sale_price}, {self.cost})" def __str__(self): return self.description diff --git a/Examples/example_7_class_attributes.py b/Examples/example_7_class_attributes.py index 3de7226..234b9ee 100644 --- a/Examples/example_7_class_attributes.py +++ b/Examples/example_7_class_attributes.py @@ -2,10 +2,10 @@ class Condition(Enum): - NEW = 1 - GOOD = 0.8 - OKAY = 0.5 - BAD = 0.2 + NEW = 0 + GOOD = 1 + OKAY = 2 + BAD = 3 class MethodNotAllowed(Exception): @@ -52,16 +52,20 @@ def service(self, spent, sale_price=None, condition=None): self.condition = condition +class Tricycle(Bike): + num_wheels = 3 + + if __name__ == '__main__': - bike1 = Bike('Univega Alpina, orange', Condition.OKAY, sale_price=500, cost=100) - bike2 = Bike('Raleigh Talus 2', Condition.BAD, sale_price=20) + bike = Bike('Univega Alpina, orange', Condition.OKAY, sale_price=500, cost=100) + trike = Tricycle('Raleigh Talus 2', Condition.BAD, sale_price=20) # All print 2 - print(bike2.num_wheels) - print(bike1.num_wheels) + print(trike.num_wheels) + print(bike.num_wheels) print(Bike.num_wheels) print(Bike.count) # 2 - del bike1 + del bike print(Bike.count) # 1 diff --git a/Examples/example_8_decorators.py b/Examples/example_8_decorators.py index ccf0f06..58df1ed 100644 --- a/Examples/example_8_decorators.py +++ b/Examples/example_8_decorators.py @@ -1,12 +1,12 @@ -from datetime import datetime +import random from enum import Enum class Condition(Enum): - NEW = 1 - GOOD = 0.8 - OKAY = 0.5 - BAD = 0.2 + NEW = 0 + GOOD = 1 + OKAY = 2 + BAD = 3 class MethodNotAllowed(Exception): @@ -14,6 +14,8 @@ class MethodNotAllowed(Exception): class Bike(object): + counter = 0 + def __init__(self, description, condition, sale_price, cost=0): self.description = description self.condition = condition @@ -21,6 +23,8 @@ def __init__(self, description, condition, sale_price, cost=0): self.cost = cost self.sold = False + type(self).counter += 1 + self.id = self.counter def update_sale_price(self, sale_price): if self.sold: @@ -52,35 +56,44 @@ def profit(self): return self.sale_price - self.cost @staticmethod - def age(year): - current_year = datetime.now().year - age = current_year - year - if age < 1: - return "New" - elif age < 5: - return "Recent" - elif age < 40: - return "Old" - else: - return "Vintage" + def get_test_bike(): + return Bike( + description="A test bike", + condition=random.choice(list(Condition)), + sale_price=random.randrange(100, 500, 25), + cost=random.randrange(0, 100, 10) + ) @classmethod - def get_default_bike(cls): + def get_test_object(cls): return cls( - description="A default bike", - condition=Condition.GOOD, - sale_price=100 + description=f"{cls.__name__} {cls.counter + 1}", + condition=random.choice(list(Condition)), + sale_price=random.randrange(100, 500, 25), + cost=random.randrange(0, 100, 10) ) + def __str__(self): + return f"{self.description}: selling for ${self.sale_price}, cost: ${self.cost} ({self.condition.name.lower()})" + + def __repr__(self): + return f"{type(self).__name__}({self.description!r}, {self.condition}, {self.sale_price}, {self.cost})" -if __name__ == '__main__': - bike = Bike.get_default_bike() # Class method +class Trike(Bike): + counter = 0 + + +if __name__ == '__main__': + bike = Bike.get_test_bike() # Class method + print(bike) bike.sell() - print(bike.profit) # Call property + print(bike.profit) # Call property - # Call static methods - print(bike.age(1975)) # Vintage - print(Bike.age(2019)) # Recent + # Call methods on subclass + print(Trike.get_test_bike()) # staticmethod + trike = Trike.get_test_object() # classmethod + print(trike) + print([bike, trike]) # Call repr \ No newline at end of file diff --git a/Examples/example_9_getters_setters.py b/Examples/example_9_getters_setters.py index 2c38c2e..8922c13 100644 --- a/Examples/example_9_getters_setters.py +++ b/Examples/example_9_getters_setters.py @@ -1,11 +1,12 @@ +import random from enum import Enum class Condition(Enum): - NEW = 1 - GOOD = 0.8 - OKAY = 0.5 - BAD = 0.2 + NEW = 0 + GOOD = 1 + OKAY = 2 + BAD = 3 class MethodNotAllowed(Exception): @@ -13,8 +14,6 @@ class MethodNotAllowed(Exception): class Bike(object): - min_profit = 10 - def __init__(self, description, condition, sale_price, cost=0): self.description = description self.condition = condition @@ -29,8 +28,7 @@ def sale_price(self): @sale_price.setter def sale_price(self, sale_price): - if self.sold: - raise MethodNotAllowed('Bike has already been sold') + ... # Add some validation self._sale_price = sale_price def sell(self): @@ -47,27 +45,27 @@ def service(self, spent, sale_price=None, condition=None): """ self.cost += spent if sale_price: - self.update_sale_price(sale_price) + self.sale_price = sale_price if self.condition: self.condition = condition @classmethod - def get_default_bike(cls): + def get_test_object(cls): return cls( - description="A default bike", - condition=Condition.GOOD, - sale_price=100 + description=f"A test {cls.__name__}", + condition=random.choice(list(Condition)), + sale_price=random.randrange(100, 500, 25), + cost=random.randrange(0, 100, 10) ) if __name__ == '__main__': - bike = Bike.get_default_bike() # Class method - - print(bike.sale_price) # 100 + bike = Bike.get_test_object() # Class method - bike.sale_price = 300 - print(bike.sale_price) # 300 + print(bike.sale_price) # Calls getter/property + bike.sale_price = 1000 # Calls setter + print(bike.sale_price) # 1000 bike.sell() - bike.sale_price = 200 # Exception raised + bike.sale_price = 999 # Exception raised diff --git a/README.md b/README.md index 7cee9c9..80ba153 100644 --- a/README.md +++ b/README.md @@ -1,63 +1,48 @@ # Object-Oriented Programming in Python Live Training -This is the code for the *Safari Live Training* - **Object-Oriented Programming in Python** presented by Arianne Dee - -**Note**: If you're looking for the project code for a specific date in the past, -look for the specific class [here](https://github.com/ariannedee/oop-python/releases) +This is the code for the *O'Reilly Live Training* - **Object-Oriented Programming in Python** presented by Arianne Dee Before the class, please follow these instructions: -1. [Install Python](#1-install-python-36-or-higher) +1. [Install Python](#1-install-python-38-or-higher) 1. [Check that Python was installed properly](#2-make-sure-that-python-is-properly-installed) 1. [Install PyCharm](#3-download-pycharm-community-edition) 1. [Download the code](#4-download-the-course-files) 5. [Download the resources](#5-at-the-beginning-of-class-download-the-resources) ## Set up instructions -### 1. Install Python 3.6 or higher +### 1. Install Python 3.8 or higher Go to https://www.python.org/downloads/ Click the yellow button at the top to download the latest version of Python. -#### On Mac or Linux Follow the prompts and install using the default settings. -#### On Windows -The default settings don't add Python to your PATH -so your computer doesn't know where to look for it when Python runs -(for some inexplicable reason). - -##### If you're just installing Python now -Follow the instructions here: [Windows Python installer instructions](docs/WININSTALL.md) - -##### If you've already installed Python with the default settings -Follow the instructions here: [Add Python to PATH variable in Windows](docs/WINSETPATH.md) - ### 2. Make sure that Python is properly installed -1. Open the *Command Prompt* application in Windows +1. Open the *PowerShell* application in Windows or *Terminal* on Mac or Linux -1. Type `python --version` and press enter - -1. Type `python3 --version` and press enter +1. Type `python --version` and press enter +2. Type `python3 --version` and press enter +3. Type `py --version` and press enter -1. One or both of those commands should print -a Python version of 3.6 or higher +At least one of those commands should print +a Python version of 3.8 or higher (whichever version you just downloaded). - If it doesn't, you have to follow instructions to - [add Python to your PATH variable](docs/WINSETPATH.md). **Note:** -You can now type just the `python` or `python3` command -in *Command Prompt* or *Terminal* -to run the Python interpreter. +You can now type just the `python`, `python3` or `py` command +in *PowerShell* or *Terminal* to run the Python console. You can also run a *.py* file by running -`python filename.py` +` filename.py` -### 3. Download PyCharm (Community Edition) +### 3. Download PyCharm Download here: https://www.jetbrains.com/pycharm/download/ Install, open, and use the default settings. +*Note*: It comes with a 30-day free trial of professional features. +These are not needed for the course and the free features (or the Community edition) will suffice. + ### 4. Download the course files If you're viewing this on GitHub already, stay on this page. Otherwise, go to the GitHub repository: https://github.com/ariannedee/oop-python @@ -68,7 +53,7 @@ Clone the repository. #### If you don't know git: 1. Click the "Clone or download" (green) button at the top-right of the page 2. Click "Download ZIP" -3. Unzip it and move the **oop-python-master** folder to a convenient location +3. Unzip it and move the **oop-python-main** folder to a convenient location ### 5. At the beginning of class, download the resources When you have signed in to the class, @@ -78,33 +63,20 @@ for a resource package that has PyCharm shortcuts, links, and a Python 2 to 3 co ## FAQs ### Can I use Python 2? -Yes. There are not many differences for this class. +No, nobody should be using Python 2 anymore. ### Can I use a different code editor besides PyCharm? Jupyter notebooks are not ideal since we'll be working from multiple folders throughout the class. -Other IDEs like VS Code, Atom, and Spyder will work, but they are only recommended if you are already know it +Other IDEs like VS Code, Atom, and Spyder are fine, but they are only recommended if you are already know it and are comfortable navigating to different files and running commands in the command line. -If it has syntax highlighting for Python, that is ideal. ### PyCharm can't find Python 3 -On a Mac: -- Go to **PyCharm** > **Preferences** - -On a PC: -- Go to **File** > **Settings** - -Once in Settings: -1. Go to **Project: oop-python** > **Project Interpreter** -1. Look for your Python version in the Project Interpreter dropdown -1. If it's not there, click **gear icon** > **Add...** -1. In the new window, select **System Interpreter** on the left, and then look for the Python version in the dropdown -1. If it's not there, click the **...** button and navigate to your Python location +1. On the bottom right of PyCharm, click on the Python Interpreter and select one from the list +1. If it's not there, click **Add New Interpreter** > **Add Local Interpreter...** +1. Try to select an existing Python system interpreter and then look for the Python version in the dropdown (exact instructions differ depending on PyCharm version) +1. If it's not there, click the **...** or **folder icon** button and navigate to your Python location - To find where Python is located, [look in these directories](docs/PATH_LOCATIONS.md) - You may have to search the internet for where Python gets installed by default on your operating system - -### Do you offer private Python help? -Yes, email **arianne.dee.studios at gmail.com** if you have any questions -or would like to set up some remote training. diff --git a/Refactoring/refactoring_1_procedural.py b/Refactoring/refactoring_1_procedural.py index 1986880..26e902b 100644 --- a/Refactoring/refactoring_1_procedural.py +++ b/Refactoring/refactoring_1_procedural.py @@ -2,25 +2,27 @@ Simulate a simple board game. There are 2 players. Each player takes turn rolling a die and moving that number of spaces. -The first person to space 100 wins. +The first person to space 50 wins. """ -import random +from random import randint if __name__ == '__main__': player_1_score = 0 player_2_score = 0 while True: - player_1_roll = random.randint(1, 6) + player_1_roll = randint(1, 6) player_1_score += player_1_roll - print(f"Player 1 score: {player_1_score} (rolled a {player_1_roll})") - if player_1_score >= 100: + print(f"Player 1: {player_1_score} (rolled a {player_1_roll})") + + if player_1_score >= 50: print("Player 1 wins!") break - player_2_roll = random.randint(1, 6) + player_2_roll = randint(1, 6) player_2_score += player_2_roll - print(f"Player 2 score: {player_2_score} (rolled a {player_2_roll})") - if player_2_score >= 100: + print(f"Player 2: {player_2_score} (rolled a {player_2_roll})") + + if player_2_score >= 50: print("Player 2 wins!") - break + break \ No newline at end of file diff --git a/Refactoring/refactoring_2_dry.py b/Refactoring/refactoring_2_dry.py index 4557956..a9dd487 100644 --- a/Refactoring/refactoring_2_dry.py +++ b/Refactoring/refactoring_2_dry.py @@ -2,25 +2,29 @@ Simulate a simple board game. There are 2 players. Each player takes turn rolling a die and moving that number of spaces. -The first person to space 100 wins. +The first person to space 50 wins. """ -import random +from random import randint - -def play_game(): - scores = [0, 0] +def play_game(num_players=2, target_score=50): + scores = [0 for i in range(num_players)] while True: for i, score in enumerate(scores): player_num = i + 1 - roll = random.randint(1, 6) + roll = randint(1, 6) score += roll scores[i] = score - print(f"Player {player_num} score: {score} (rolled a {roll})") - if score >= 100: + print(f"Player {player_num}: {score} (rolled a {roll})") + + if score >= target_score: print(f"Player {player_num} wins!") return - if __name__ == '__main__': - play_game() + print("------ GAME 1 START ------") + play_game(3, 40) + print("------ GAME 1 END ------") + print("------ GAME 2 START ------") + play_game(4, 30) + print("------ GAME 2 END ------") diff --git a/Refactoring/refactoring_3_abstraction.py b/Refactoring/refactoring_3_abstraction.py index 6d95bb6..773b8f8 100644 --- a/Refactoring/refactoring_3_abstraction.py +++ b/Refactoring/refactoring_3_abstraction.py @@ -2,47 +2,44 @@ Simulate a simple board game. There are 2 players. Each player takes turn rolling a die and moving that number of spaces. -The first person to space 100 wins. +The first person to space 50 wins. """ -import random - +from random import randint class Player: - def __init__(self, player_num): - self.player_num = player_num - self._score = 0 - - @staticmethod - def roll_die(): - return random.randint(1, 6) + def __init__(self, num, score=0): + self.num = num + self.score = score def take_turn(self): - roll = self.roll_die() - self._score += roll - print(f"{self} score: {self._score} (rolled a {roll})") - - def has_won(self): - return self._score >= 100 + roll = randint(1, 6) + self.score += roll + print(f"{self}: {self.score} (rolled a {roll})") - @property - def score(self): - return self._score + def has_won(self, target_score): + return self.score >= target_score def __str__(self): - return f"Player {self.player_num}" + return f"Player {self.num}" + def __repr__(self): + return f"Player({self.num}, score={self.score})" + + +def play_game(num_players=2, target_score=50): + players = [Player(i + 1) for i in range(num_players)] -def play_game(num_players): - players = [] - for i in range(num_players): - players.append(Player(i + 1)) while True: for player in players: player.take_turn() - if player.has_won(): + if player.has_won(target_score): print(f"{player} wins!") return - if __name__ == '__main__': - play_game(3) + print("------ GAME 1 START ------") + play_game(3, 40) + print("------ GAME 1 END ------") + print("------ GAME 2 START ------") + play_game(4, 30) + print("------ GAME 2 END ------") diff --git a/Refactoring/refactoring_4_encapsulation/__init__.py b/Refactoring/refactoring_4_encapsulation/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Refactoring/refactoring_4_encapsulation/game.py b/Refactoring/refactoring_4_encapsulation/game.py index bc15049..1436793 100644 --- a/Refactoring/refactoring_4_encapsulation/game.py +++ b/Refactoring/refactoring_4_encapsulation/game.py @@ -2,19 +2,52 @@ class Game: - def __init__(self, num_players, target_score=100): + counter = 0 + + def __init__(self, num_players=2, target_score=50): + Game.counter += 1 + self.num = Game.counter self.target_score = target_score - self.players = [] - for i in range(num_players): - self.players.append(Player(i + 1)) + self.players: list[Player] = [Player(i + 1) for i in range(num_players)] - def player_won(self, player): - return player.score >= self.target_score + def run(self): + print(f"------ {self} START ------".upper()) + self._take_turns() + print(f"------ {self} END ------".upper()) - def run_game(self): + def _take_turns(self): while True: for player in self.players: player.take_turn() - if self.player_won(player): - print(f"{player} wins!") - return + + if self.game_is_over(): + print(f"{self.winner} wins!") + print(self.players) + return + + def player_won(self, player): + return player.score >= self.target_score + + def game_is_over(self): + for player in self.players: + if player.score >= self.target_score: + return True + return False + + @property + def winner(self): + max_score = 0 + max_player = None + + for player in self.players: + if player.score > max_score: + max_score = player.score + max_player = player + + return max_player + + def __str__(self): + return f"Game {self.num}" + + def __repr__(self): + return f"Game({len(self.players)}, {self.target_score})" diff --git a/Refactoring/refactoring_4_encapsulation/main.py b/Refactoring/refactoring_4_encapsulation/main.py index a61c089..a042452 100644 --- a/Refactoring/refactoring_4_encapsulation/main.py +++ b/Refactoring/refactoring_4_encapsulation/main.py @@ -2,11 +2,10 @@ Simulate a simple board game. There are 2 players. Each player takes turn rolling a die and moving that number of spaces. -The first person to space 100 wins. +The first person to space 50 wins. """ -from game import Game # In PyCharm, mark parent directory as Sources Root for imports to work +from game import Game -Game(num_players=4, target_score=20).run_game() -print("---------- END GAME 1 ---------") -Game(num_players=2, target_score=30).run_game() -print("---------- END GAME 2 ---------") +if __name__ == '__main__': + Game(3, 40).run() + Game(4, 30).run() diff --git a/Refactoring/refactoring_4_encapsulation/player.py b/Refactoring/refactoring_4_encapsulation/player.py index 859031e..9008a83 100644 --- a/Refactoring/refactoring_4_encapsulation/player.py +++ b/Refactoring/refactoring_4_encapsulation/player.py @@ -1,23 +1,28 @@ -import random +from random import randint class Player: - def __init__(self, player_num): - self.player_num = player_num - self._score = 0 - - @staticmethod - def roll_die(): - return random.randint(1, 6) - - def take_turn(self): - roll = self.roll_die() - self._score += roll - print(f"{self} score: {self._score} (rolled a {roll})") + def __init__(self, num, score=0): + self.num = num + self._score = score @property def score(self): return self._score + def take_turn(self): + roll = randint(1, 6) + self._score += roll + print(f"{self}: {self.score} (rolled a {roll})") + def __str__(self): - return f"Player {self.player_num}" + return f"Player {self.num}" + + def __repr__(self): + return f"Player({self.num}, score={self.score})" + + +if __name__ == '__main__': + player = Player(100) + player.take_turn() + player.take_turn() \ No newline at end of file diff --git a/Refactoring/refactoring_5_inheritance/__init__.py b/Refactoring/refactoring_5_inheritance/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/Refactoring/refactoring_5_inheritance/game.py b/Refactoring/refactoring_5_inheritance/game.py index 52cfbb4..3d3f857 100644 --- a/Refactoring/refactoring_5_inheritance/game.py +++ b/Refactoring/refactoring_5_inheritance/game.py @@ -1,21 +1,53 @@ -from player import Player, LuckyPlayer +from player import get_player, Player class Game: - def __init__(self, num_players, target_score=100): + counter = 0 + + def __init__(self, num_players=2, target_score=50): + Game.counter += 1 + self.num = Game.counter self.target_score = target_score - self.players = [] - for i in range(num_players - 1): - self.players.append(Player(i + 1)) - self.players.append(LuckyPlayer(num_players)) + self.players: list[Player] = [get_player(i + 1) for i in range(num_players)] - def player_won(self, player): - return player.score >= self.target_score + def run(self): + print(f"------ {self} START ------".upper()) + self._take_turns() + print(f"------ {self} END ------".upper()) - def run_game(self): + def _take_turns(self): while True: for player in self.players: player.take_turn() - if self.player_won(player): - print(f"{player} wins!") - return + + if self.game_is_over(): + print(f"{self.winner} wins!") + print(self.players) + return + + def player_won(self, player): + return player.score >= self.target_score + + def game_is_over(self): + for player in self.players: + if player.score >= self.target_score: + return True + return False + + @property + def winner(self): + max_score = 0 + max_player = None + + for player in self.players: + if player.score > max_score: + max_score = player.score + max_player = player + + return max_player + + def __str__(self): + return f"Game {self.num}" + + def __repr__(self): + return f"Game({len(self.players)}, {self.target_score})" diff --git a/Refactoring/refactoring_5_inheritance/main.py b/Refactoring/refactoring_5_inheritance/main.py index b0d493a..a042452 100644 --- a/Refactoring/refactoring_5_inheritance/main.py +++ b/Refactoring/refactoring_5_inheritance/main.py @@ -2,11 +2,10 @@ Simulate a simple board game. There are 2 players. Each player takes turn rolling a die and moving that number of spaces. -The first person to space 100 wins. +The first person to space 50 wins. """ -from game import Game # In PyCharm, mark parent directory as Sources Root for imports to work +from game import Game -Game(num_players=4, target_score=50).run_game() -print("---------- END GAME 1 ---------") -Game(num_players=2, target_score=30).run_game() -print("---------- END GAME 2 ---------") +if __name__ == '__main__': + Game(3, 40).run() + Game(4, 30).run() diff --git a/Refactoring/refactoring_5_inheritance/player.py b/Refactoring/refactoring_5_inheritance/player.py index 1055d17..6650d88 100644 --- a/Refactoring/refactoring_5_inheritance/player.py +++ b/Refactoring/refactoring_5_inheritance/player.py @@ -1,35 +1,48 @@ -import random +from random import randint class Player: - def __init__(self, player_num): - self.player_num = player_num - self._score = 0 + def __init__(self, num, score=0): + self.num = num + self._score = score + + @property + def score(self): + return self._score @staticmethod - def roll_die(): - return random.randint(1, 6) + def _roll(): + return randint(1, 6) def take_turn(self): - roll = self.roll_die() + roll = self._roll() self._score += roll - print(f"{self} score: {self._score} (rolled a {roll})") - - @property - def score(self): - return self._score + print(f"{self}: {self.score} (rolled a {roll})") def __str__(self): - return f"Player {self.player_num}" + return f"Player {self.num}" def __repr__(self): - return str(self) + return f"{type(self).__name__}({self.num}, score={self.score})" class LuckyPlayer(Player): - @staticmethod - def roll_die(): - return random.randint(3, 6) + def __init__(self, minimum_roll=3, *args, **kwargs): + print(args) + print(kwargs) + super().__init__(*args, **kwargs) + self.min_roll = minimum_roll + + def _roll(self): + return randint(self.min_roll, 6) def __str__(self): - return f"{super().__str__()} (lucky)" + base_str = super().__str__() + return f"{base_str}*" + + +def get_player(num): + if num == 2: + return LuckyPlayer(2, num, 20) + else: + return Player(num) diff --git a/bike_example.py b/bike_example.py index 48f54a5..e69de29 100644 --- a/bike_example.py +++ b/bike_example.py @@ -1,58 +0,0 @@ -""" -Bike class for use in a retail shop -""" -from enum import Enum - - -class Condition(Enum): - NEW = 1 - GOOD = 2 - OKAY = 3 - BAD = 4 - - -class MethodNotAllowed(Exception): - pass - - -class Bike(object): - def __init__(self, description, condition, sale_price, cost=0): - self.cost = cost - self.sale_price = sale_price - self.condition = condition - self.description = description - - self.sold = False - - def update_sale_price(self, new_sale_price): - if self.sold: - raise MethodNotAllowed("You cannot update the price of a sold bike") - self.sale_price = new_sale_price - - def sell(self): - self.sold = True - return self.sale_price - self.cost - - def service(self, cost, new_sale_price): - self.cost += cost - self.update_sale_price(new_sale_price) - - def __str__(self): - return f"{self.description}{' (sold)' if self.sold else ''}" - - def __repr__(self): - return f"Bike: {self} {self.condition.name}" - - -if __name__ == '__main__': - my_bike = Bike("2004 Raleigh Cruiser", Condition.GOOD, sale_price=350, cost=50) - - # Update sale price - my_bike.update_sale_price(300) - - # Sell bike - profit = my_bike.sell() - - # Determine profit - print(profit) - diff --git a/docs/WININSTALL.md b/docs/WININSTALL.md deleted file mode 100644 index 7da329b..0000000 --- a/docs/WININSTALL.md +++ /dev/null @@ -1,17 +0,0 @@ -## Installing Python on Windows -The Python installer for Windows doesn't use the optimal default settings. -Follow these instructions when running the installer. -If you have already installed Python with the default settings, -follow the instructions here instead: [add Python to the PATH variable](WINSETPATH.md) - -1. Check the *Add Python to PATH* box -2. Choose the *Customize installation* option - - -3. Keep the default settings and click *Next* - - -4. Check the *Install for all users* box if you want Python accessible by all users. -5. Customize the install location: **C:\Python37** or whatever version number you're installing -6. Click *Install* - diff --git a/docs/WINSETPATH.md b/docs/WINSETPATH.md deleted file mode 100644 index 1a195ab..0000000 --- a/docs/WINSETPATH.md +++ /dev/null @@ -1,26 +0,0 @@ -## Windows set up instruction -If you installed Python with the default options, -you will probably need to add Python to the PATH variable. -This let's your operating system know where to look for the Python executable -when you try running it. - -To add Python to your PATH variable: -1. Find the path of **python.exe** on your system. -[Look in these directories](PATH_LOCATIONS.md) or search for it. - -1. Open *System Properties* and click on the *Advanced* tab - -1. Click on *Environment Variables* - -1. Under *System variables* find and click on the *Path* variable - -1. In edit mode, go to the end of the line and add **;C:\Python37** or whatever folder *python.exe* is in. -Note the semicolon before the path; this will separate it from the previous path. - -Follow the instructions [here](../README.md#4-make-sure-that-python-is-properly-installed) -to check that the PATH variable was set properly. - -If you are having problems: - -Search the internet for "**Add python to path on Windows *10 / Vista / XP / etc***" -to find instructions for your version of Windows. diff --git a/docs/installer_1.png b/docs/installer_1.png deleted file mode 100644 index 0981136..0000000 Binary files a/docs/installer_1.png and /dev/null differ diff --git a/docs/installer_2.png b/docs/installer_2.png deleted file mode 100644 index 524eb42..0000000 Binary files a/docs/installer_2.png and /dev/null differ diff --git a/docs/installer_3.png b/docs/installer_3.png deleted file mode 100644 index 4adb09b..0000000 Binary files a/docs/installer_3.png and /dev/null differ