|
| 1 | +#Read the error, and make sure you understand what it’s telling you. |
| 2 | + |
| 3 | + |
| 4 | + |
| 5 | +class Person: |
| 6 | + def __init__(self, name: str, age: int, preferred_operating_system: str): |
| 7 | + self.name = name |
| 8 | + self.age = age |
| 9 | + self.preferred_operating_system = preferred_operating_system |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +imran = Person("Imran", 22, "Ubuntu") |
| 14 | +print(imran.name) |
| 15 | + |
| 16 | + |
| 17 | +eliza = Person("Eliza", 34, "Arch Linux") |
| 18 | +print(eliza.name) |
| 19 | + |
| 20 | +def is_adult(person: Person) -> bool: |
| 21 | + return person.age >= 18 |
| 22 | + |
| 23 | +print(is_adult(imran)) |
| 24 | + |
| 25 | + |
| 26 | +def address(person: Person) -> str: |
| 27 | + return person.address |
| 28 | + |
| 29 | + |
| 30 | +#EXERCISE 1: |
| 31 | +#Add the is_adult code to the file you saved earlier. |
| 32 | +#Run it through mypy - notice that no errors are reported - mypy understands that Person has a property named age so is happy with the function. |
| 33 | +# Write a new function in the file that accepts a Person as a parameter and tries to access a property that doesn’t exist. Run it through mypy and check that it does report an error. |
| 34 | + |
| 35 | +# SOLUTION: |
| 36 | +# After run class-and-object.py, I get the following mypy errors: |
| 37 | +# class-and-object.py:12: error: "Person" has no attribute "address" |
| 38 | +# It indicates that the Person class does not have an attribute named address. |
| 39 | + |
| 40 | +#EXERCISE 2: |
| 41 | +# Add the is_adult code to the file you saved earlier |
| 42 | +# Run it through mypy - notice that no errors are reported - mypy understands that Person has a property named age so is happy with the function. |
| 43 | + |
| 44 | +# Write a new function in the file that accepts a Person as a parameter and tries to access a property that doesn’t exist. Run it through mypy and check that it does report an error. |
| 45 | +# When running mypy, I get the following error: |
| 46 | +# Class-and-object.py:27: error: "Person" has no attribute "address" [attr-defined] |
| 47 | +# Found 1 error in 1 file (checked 1 source file) |
| 48 | +# This error indicates that the Person class does not have an attribute named address. |
0 commit comments