-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasses.py
More file actions
440 lines (347 loc) · 15.8 KB
/
Copy pathclasses.py
File metadata and controls
440 lines (347 loc) · 15.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
"""
This is where I am going to be learning about classes, as taught in Python Crash Course 2nd
Edition.
"""
# Almost everything can be modeled using classes.
class Dog:
"""A class that models a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulate a dog rolling over in response to a command."""
print(f"{self.name} rolled over.")
# A function that's part of a class is called a method. The __init__ method is a special method
# that Python runs automatically whenever we create a new instance based on the dog class. It
# must be started with 2 underscores and followed by 2 underscores.
# The self parameter in the __init__ method is required in the method definition, and must be the
# first parameter.
# A class can be thought of as a set of instructions for how to make an instance.
# Making an instance representing a specific dog can be done like this:
my_dog = Dog('Willie', 6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
# After we create an instance from the Dog class, we can use dot notation to call any method defined
# in dog.
my_dog.sit()
my_dog.roll_over()
# To call a method, give the name of the instance (here, my_dog) and the method you want to call,
# seperated by a dot.
# You can create as many instances from a class as you need.
your_dog = Dog('Lucy', 3)
print(f"My dog's name is {your_dog.name}.")
print(f"My dog is {your_dog.age} years old.")
your_dog.sit()
# Even if we used the same name and age for the second dog as we did for the first, Python would
# still create a seperate instance of the Dog class.
# RESTAURANT PRACTICE:
# class Restaurant:
# """Class for a restaurant."""
# def __init__(self, name, food):
# """Initialize the class attributes."""
# self.name = name
# self.food = food
# def describe_restaurant(self):
# """Describes an instance of the restaurant class."""
# print(f"The restaurant {self.name.title()} is a {self.food} place.")
# def open_restaurant(self):
# """Prints a message saying that the restaurant has opened."""
# print(f"{self.name.title()} has opened.")
# buckeyes = Restaurant('buckeyes', 'steak')
# buckeyes.describe_restaurant()
# buckeyes.open_restaurant()
# USERS PRACTICE:
# class User:
# """Class for a user profile."""
# def __init__(self, first_name, last_name, age, gender):
# """Initialize the values for the user."""
# self.first_name = first_name
# self.last_name = last_name
# self.age = age
# self.gender = gender
# def describe_user(self):
# """Describes the user."""
# print(f"{self.first_name} {self.last_name} is {self.age}, and is a {self.gender}.")
# def greet_user(self):
# """Greets the user."""
# print(f"Hello, {self.first_name}. Welcome back.")
# user1 = User('Alice', 'Oates', 13, 'female')
# user1.describe_user()
# user1.greet_user()
# user2 = User('Rob', 'Springs', 27, 'male')
# user2.describe_user()
# user2.greet_user()
# You can modify the attributes of an instance directly or write methods that update attributes
# in specific ways.
# When an instance is created, attributes can be defined without being passed in as parameters.
# These attributes can be defined in the __init__() method, where they are assigned a defualt value.
class Car:
"""A class to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
my_new_car = Car('audi', 'a4', 2019)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()
# When changing an attribute's value, you have three ways to do this. You can change the value
# directly through an instance, set the value through a method, or increment the value through
# a method.
# Changing it directly:
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
# Changing it via a method:
# class Car:
# """A class to represent a car."""
# def __init__(self, make, model, year):
# """Initialize attributes to describe a car."""
# self.make = make
# self.model = model
# self.year = year
# self.odometer_reading = 0
# def get_descriptive_name(self):
# """Return a neatly formatted descriptive name."""
# long_name = f"{self.year} {self.make} {self.model}"
# return long_name.title()
# def read_odemeter(self):
# """Print a statement showing the car's mileage."""
# print(f"This car has {self.odometer_reading} miles on it.")
# def update_odometer(self):
# """
# Set the odometer reading to the given value.
# Reject if it tries to roll the odometer back.
# """
# if mileage >= self.odometer_reading:
# self.odometer_reading = mileage
# else:
# print("You can't roll back an odometer.")
# def increment_odemeter(self):
# """Add the given amount to the odometer reading."""
# self.odometer_reading += miles
# NOTE: You can use methods like this to control how users of your program update
# values, but anyone with access to the program can set the odometer reading to any
# value by accessing the attribute directly. Effective security takes extreme attention
# to detail in addition to the basic checks like those shown here.
# NUMBER SERVED PRATICE:
class Restaurant:
"""Class for a restaurant."""
def __init__(self, name, food):
"""Initialize the class attributes."""
self.name = name
self.food = food
self.number_served = 0
def describe_restaurant(self):
"""Describes an instance of the restaurant class."""
print(f"The restaurant {self.name.title()} is a {self.food} place.")
def open_restaurant(self):
"""Prints a message saying that the restaurant has opened."""
print(f"{self.name.title()} has opened.")
def set_number_served(self, number_served):
"""Allows someone to set the number of people they've served."""
self.number_served = number_served
def increment_number_served(self, additional_served):
"""Allows someone to increment the number of people served."""
self.number_served += additional_served
buckeyes = Restaurant('buckeyes', 'steak')
print(f"The restaurant has served {buckeyes.number_served} people.")
buckeyes.number_served += 1
print(f"The restaurant has served {buckeyes.number_served} people.")
buckeyes.set_number_served(0)
print(f"\nThe restaurant has served {buckeyes.number_served} people.")
buckeyes.increment_number_served(12)
print(f"\nThe restaurant has served {buckeyes.number_served} people.")
# LOGIN ATTEMPTS PRACTICE:
class User:
"""Class for a user profile."""
def __init__(self, first_name, last_name, age, gender):
"""Initialize the values for the user."""
self.first_name = first_name
self.last_name = last_name
self.age = age
self.gender = gender
self.login_attempts = 0
def describe_user(self):
"""Describes the user."""
print(f"{self.first_name} {self.last_name} is {self.age}, and is a {self.gender}.")
def greet_user(self):
"""Greets the user."""
print(f"Hello, {self.first_name}. Welcome back.")
def increment_login_attempts(self):
"""Increment the number of login attempts by 1."""
self.login_attempts += 1
def reset_login_attempts(self):
"""Resets the number of login attempts to 0."""
self.login_attempts = 0
user1 = User('Alice', 'Oates', 13, 'female')
print(f"{user1.first_name} has tried to log in {user1.login_attempts} times.")
user1.increment_login_attempts()
print(f"{user1.first_name} has tried to log in {user1.login_attempts} times.")
user1.increment_login_attempts()
print(f"{user1.first_name} has tried to log in {user1.login_attempts} times.")
user1.increment_login_attempts()
print(f"{user1.first_name} has tried to log in {user1.login_attempts} times.")
user1.increment_login_attempts()
print(f"{user1.first_name} has tried to log in {user1.login_attempts} times.")
user1.reset_login_attempts()
print(f"{user1.first_name} has tried to log in {user1.login_attempts} times.")
# If the class you're writing is a specialized version of another class, you can use
# inheritance. When a class inherits from another, it takes on the attributes and
# methods of the first parent class (the original class is called the parent class,
# and the new class is the child class). The child class can inherit any or all of the
# attributes and methods of its parent class, but can also define new attributes and
# methods of its own.
# When writing a new class based on an existing class, you'll often want to call the __init__()
# method from the parent class. This will initialize any attributes that were defined in the
# parent __init__() method and make them available in the child class.
class ElectricCar(Car):
"""A child class of the parent Car, specific to electric cars."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
self.battery_size = 75
def describe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")
my_tesla = ElectricCar('tesla', 'model s', 2019)
print(my_tesla.get_descriptive_name())
my_tesla.describe_battery()
# You can override any method from the parent class that doesn't fit what you're trying to do
# with the child class. To do this, create a method in the child class with the same name as the
# original method in the parent class.
# When creating classes, you may notice that more and more detail is being added to the class, and
# that your files are becoming lengthy. Sometimes in these situations, part of a class can be
# broken off and written as another class. You can break your large class into smaller classes that
# work together. For example, instead of having a battery function in the electric car class, you
# could instead have a seperate class called battery, and then include this line of code:
# self.battery = Battery()
# in the __init__() method for the electric car class.
# When using the describe battery function now in the battery class, we would have to run this
# line of code:
# my_tesla.battery.describe_battery()
# ICE CREAM STAND PRACTICE:
class IceCreamStand(Restaurant):
"""A child class modeling an ice cream stand that inherits from the Restaurant parent class."""
def __init__(self, name, food):
"""Initialize the values for the child class."""
super().__init__(name, food)
self.flavors = ['chocolate', 'vanilla', 'lemon', 'mint chocolate chip', 'strawberry']
def list_flavors(self):
"""Lists all of the flavors sold at the ice cream stand."""
print("These are the flavors we have:")
for flavor in self.flavors:
print(f" -{flavor.title()}")
ice_cream_stand = IceCreamStand("Jerry's", 'ice cream')
ice_cream_stand.list_flavors()
# ADMIN PRACTICE:
class Admin(User):
"""A user with administrative privileges."""
def __init__(self, first_name, last_name, age, gender):
"""Initialize the admin."""
super().__init__(first_name, last_name, age, gender)
self.privileges = []
def show_privileges(self):
"""Display the privileges this administrator has."""
print("\nPrivileges:")
for privilege in self.privileges:
print(f" -{privilege}")
admin = Admin('bob', 'ginkle', 35, 'male')
admin.privileges = ["some stuff that admins can do", "some things that they can't"]
admin.show_privileges()
# PRIVILEGES PRACTICE:
class Privileges:
"""A class that lists the privileges that an admin would have."""
def __init__(self, privileges=[]):
self.privileges = privileges
def show_privileges(self):
"""Show the privileges that an admin has."""
print("\nPrivileges:")
if self.privileges:
for privilege in self.privileges:
print(f" -{privilege}")
else:
print("- This user has no privileges.")
another_admin = Admin('jessica', 'wilds', 24, 'female')
another_admin.privileges = ['can ban users', 'can delete posts', 'can moderate discussions']
another_admin.show_privileges()
# As you add more functionality to your classes, your files can get long. To help, Python lets
# you store classes in modules and import the classes you need into your main program.
# The syntax for this is:
# from module_name import ClassName
# You can store as many classes as you need in a single module, although each class in a module
# should be related in some way.
# To import mutiple classes from a module, use the following syntax:
# from module_name import ClassName1, ClassName2
# You can also import an entire module and then access the classes you need using dot notation.
# import car
# some_car = car.Car('car', 'model', 'year')
# print(some_car.get_descriptive_name())
# Syntax:
# car.Car = module_name.ClassName
# You can also import every class from a module using the following syntax:
# from module_name import *
# Though it is not recommended. First of all, it's helpful to be able to read the import
# statements at the top of a file and get a clear sense of which classes a program uses.
# With the * operator, it's unclear what classses you're importing. If you need to import
# many classes from a module, you're better off importing the entire module and using the
# module_name.ClassName syntax. This can also help avoid potential naming conflicts.
# You can also use aliases when importing classes if you need to:
# from module_name import ClassName as alias
# The Python standard library is a set of modules included with every Python install. You can
# use any function or class in the standard libary by using an import statement. For example,
# you can import the random module (you already know what it is).
# NOTE: You can also download modules from external sources. You'll see a number of these examples
# in part II, where we'll need external modules to complete each project.
# DICE PRACTICE:
import random
class Die:
"""A class to model the rolling of die."""
def __init__(self, sides=6):
self.sides = sides
def roll_die(self):
"""Rolls the die."""
return f"You rolled a {random.randint(1, self.sides)}"
d6 = Die()
d10 = Die(10)
d20 = Die(20)
results = []
for roll in range(10):
result = d6.roll_die()
results.append(result)
print("\nHere are the results of rolling a D6:")
for result in results:
print(f" -{result}")
results = []
for roll in range(10):
result = d10.roll_die()
results.append(result)
print("\nHere are the results of rolling a D10:")
for result in results:
print(f" -{result}")
results = []
for roll in range(10):
result = d20.roll_die()
results.append(result)
print("\nHere are the results of rolling a D20:")
for result in results:
print(f" -{result}")
# LOTTERY PRACTICE:
possibilities = [1, 24, 17, 90, 34, 548, 3, 75, 111, 85, 'a', 'z', 'q', 'y', 'i']
winning_ticket = []
while len(winning_ticket) < 4:
chosen_item = random.choice(possibilities)
if chosen_item not in winning_ticket:
winning_ticket.append(chosen_item)
print(f"The winning ticket is {winning_ticket}!")