forked from huangsam/ultimate-python
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_class.py
More file actions
Latest commit
79 lines (58 loc) · 2.67 KB
/
Copy pathbasic_class.py
File metadata and controls
79 lines (58 loc) · 2.67 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
"""
A class is made up of methods and state. This allows code and data to be
combined as one logical entity. This module defines a basic car class,
creates a car instance and uses it for demonstration purposes.
"""
frominspectimportisfunction, ismethod, signature
classCar:
"""Basic definition of a car.
We begin with a simple mental model of what a car is. That way, we
can start exploring the core concepts that are associated with a
class definition.
"""
def__init__(self, make: str, model: str, year: int, miles: float) ->None:
"""Constructor logic."""
self.make=make
self.model=model
self.year=year
self.miles=miles
def__repr__(self) ->str:
"""Formal representation for developers."""
returnf"<Car make={self.make} model={self.model} year={self.year}>"
def__str__(self) ->str:
"""Informal representation for users."""
returnf"{self.make}{self.model} ({self.year})"
defdrive(self, rate_in_mph: int) ->str:
"""Drive car at a certain rate in MPH."""
returnf"{self} is driving at {rate_in_mph} MPH"
defmain() ->None:
# Create a car with the provided class constructor
car=Car("Bumble", "Bee", 2000, 200000.0)
# Formal representation is good for debugging issues
assertrepr(car) =="<Car make=Bumble model=Bee year=2000>"
# Informal representation is good for user output
assertstr(car) =="Bumble Bee (2000)"
# Call a method on the class constructor
assertcar.drive(75) =="Bumble Bee (2000) is driving at 75 MPH"
# As a reminder: everything in Python is an object! And that applies
# to classes in the most interesting way - because they're not only
# subclasses of object - they are also instances of object. This
# means that we can modify the `Car` class at runtime, just like any
# other piece of data we define in Python
assertissubclass(Car, object) andisinstance(Car, object)
# To emphasize the idea that everything is an object, let's look at
# the `drive` method in more detail
driving=getattr(car, "drive")
# The variable method is the same as the instance method
assertdriving==car.drive
# The variable method is bound to the instance
assertdriving.__self__==car
# That is why `driving` is considered a method and not a function
assertismethod(driving) andnotisfunction(driving)
# And there is only one parameter for `driving` because `__self__`
# binding is implicit
driving_params=signature(driving).parameters
assertlen(driving_params) ==1
assert"rate_in_mph"indriving_params
if__name__=="__main__":
main()