Skip to content

Commit 7044571

Browse files
committed
Magic Object Methods module completed
1 parent e562870 commit 7044571

File tree

4 files changed

+160
-0
lines changed

4 files changed

+160
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# Python Object Oriented Programming by Joe Marini course example
2+
# Using the __str__ and __repr__ magic methods
3+
4+
5+
class Book:
6+
def __init__(self, title, author, price):
7+
super().__init__()
8+
self.title = title
9+
self.author = author
10+
self.price = price
11+
self._discount = 0.1
12+
13+
# The __str__ function is used to return a user-friendly string
14+
# representation of the object
15+
def __str__(self):
16+
return f"{self.title} by {self.author}, costs {self.price}"
17+
18+
19+
# __getattribute__ called when an attr is retrieved. Don't
20+
# directly access the attr name otherwise a recursive loop is created
21+
# def __getattribute__(self, name):
22+
# if name == "price":
23+
# p = super().__getattribute__("price")
24+
# d = super().__getattribute__("_discount")
25+
# return p - (p*d)
26+
# return super().__getattribute__(name)
27+
28+
29+
# __setattr__ called when an attribute value is set. Don't set the attr
30+
# directly here otherwise a recursive loop causes a crash
31+
def __setattr__(self, name, value):
32+
if name == "price":
33+
if type(value) is not float:
34+
raise ValueError("price attribute needs to be float.")
35+
return super().__setattr__(name, value)
36+
37+
38+
# __getattr__ called when __getattribute__ lookup fails
39+
# you can pretty much generate attributes on the fly with this method
40+
def __getattr__(self, name):
41+
return name + " is not here"
42+
43+
b1 = Book("War and Peace", "Leo Tolstoy", 39.95)
44+
b2 = Book("The Catcher in the Rye", "JD Salinger", 29.95)
45+
46+
# b1.price =35
47+
# print(b1)
48+
49+
# b2.price = 40
50+
# b2.price = float(40)
51+
# print(b2)
52+
53+
print(b1.blahblah)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Python Object Oriented Programming by Joe Marini course example
2+
# Using the __str__ and __repr__ magic methods
3+
4+
5+
class Book:
6+
def __init__(self, title, author, price):
7+
super().__init__()
8+
self.title = title
9+
self.author = author
10+
self.price = price
11+
12+
def __str__(self):
13+
return f"{self.title} by {self.author}, costs {self.price}"
14+
15+
# the __call__ method can be used to call the object like a function
16+
def __call__(self, title, author, price):
17+
self.title = title
18+
self.author = author
19+
self.price = price
20+
21+
22+
23+
b1 = Book("War and Peace", "Leo Tolstoy", 39.95)
24+
b2 = Book("The Catcher in the Rye", "JD Salinger", 29.95)
25+
26+
# call the object as if it were a function
27+
print(b1)
28+
b1("Harry Potter", "JK.Rowling", 50.60)
29+
print(b1)
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
# Python Object Oriented Programming by Joe Marini course example
2+
# Using the __str__ and __repr__ magic methods
3+
4+
5+
class Book:
6+
def __init__(self, title, author, price):
7+
super().__init__()
8+
self.title = title
9+
self.author = author
10+
self.price = price
11+
12+
# the __eq__ method checks for equality between two objects
13+
def __eq__(self, value):
14+
if not isinstance(value, Book):
15+
raise ValueError("can't compare Book to non-Book.")
16+
return (self.title == value.title and
17+
self.author == value.author and
18+
self.price == value.price)
19+
20+
# the __ge__ establishes >= relationship with another obj
21+
def __ge__(self, value):
22+
if not isinstance(value, Book):
23+
raise ValueError("can't compare Book to non-Book.")
24+
return self.price >= value.price
25+
26+
# the __lt__ establishes < relationship with another obj
27+
def __lt__(self, value):
28+
if not isinstance(value, Book):
29+
raise ValueError("can't compare Book to non-Book.")
30+
return self.price < value.price
31+
32+
33+
b1 = Book("War and Peace", "Leo Tolstoy", 39.95)
34+
b2 = Book("The Catcher in the Rye", "JD Salinger", 29.95)
35+
b3 = Book("War and Peace", "Leo Tolstoy", 39.95)
36+
b4 = Book("To Kill a Mockingbird", "Harper Lee", 24.95)
37+
38+
# Check for equality
39+
print(b1 == b3)
40+
print(b1 == b2)
41+
# print(b1 == 42)
42+
43+
# Check for greater and lesser value
44+
print(b1 >= b2)
45+
print(b1 < b2)
46+
47+
# Now we can sort them too
48+
# python now will sort them by price ascending order
49+
books = [b1, b2, b3, b4]
50+
books.sort()
51+
print([book.title for book in books])
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Python Object Oriented Programming by Joe Marini course example
2+
# Using the __str__ and __repr__ magic methods
3+
4+
5+
class Book:
6+
def __init__(self, title, author, price):
7+
super().__init__()
8+
self.title = title
9+
self.author = author
10+
self.price = price
11+
12+
# use the __str__ method to return a string
13+
def __str__(self):
14+
return f"{self.title} by {self.author} costs {self.price}"
15+
16+
# use the __repr__ method to return an obj representation (for debugging purpose)
17+
def __repr__(self):
18+
return f"title: {self.title}, author: {self.author}, price: {self.price}"
19+
20+
b1 = Book("War and Peace", "Leo Tolstoy", 39.95)
21+
b2 = Book("The Catcher in the Rye", "JD Salinger", 29.95)
22+
23+
print(b1)
24+
print(b2)
25+
26+
print(str(b2))
27+
print(repr(b2))

0 commit comments

Comments
 (0)