Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 74b07b1

Browse files
committed
Magic methods code
1 parent 1b35d8c commit 74b07b1

File tree

2 files changed

+101
-1
lines changed

2 files changed

+101
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,4 +37,5 @@ files, and the full tutorial for each collection of code is available below.
3737
30. [Abstract Base Classes](https://vegibit.com/python-abstract-base-classes/)
3838
31. [Multiple Inheritance In Python](https://vegibit.com/multiple-inheritance-in-python/)
3939
32. [Python Interface Design Pattern](https://vegibit.com/python-interface-design-pattern/)
40-
33. [Composition Over Inheritance](https://vegibit.com/composition-over-inheritance/)
40+
33. [Composition Over Inheritance](https://vegibit.com/composition-over-inheritance/)
41+
34. [What Are Python Magic Methods](https://vegibit.com/what-are-python-magic-methods/)

magicmethods.py

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
class Book():
2+
def __init__(self, title, author, price):
3+
super().__init__()
4+
self.title = title
5+
self.author = author
6+
self.price = price
7+
8+
def __str__(self):
9+
return f'{self.title} by {self.author}, costs {self.price}'
10+
11+
def __repr__(self):
12+
return f'title={self.title},author={self.author},price={self.price}'
13+
14+
def __eq__(self, value):
15+
if not isinstance(value, Book):
16+
raise ValueError('Can\'t compare book to non-book type')
17+
18+
return (self.title == value.title and
19+
self.author == value.author and
20+
self.price == value.price)
21+
22+
def __ge__(self, value):
23+
if not isinstance(value, Book):
24+
raise ValueError('Can\'t compare book to non-book type')
25+
26+
return self.price >= value.price
27+
28+
def __lt__(self, value):
29+
if not isinstance(value, Book):
30+
raise ValueError('Can\'t compare book to non-book type')
31+
32+
return self.price < value.price
33+
34+
def __getattribute__(self, name):
35+
if (name == 'price'):
36+
price = super().__getattribute__('price')
37+
discount = super().__getattribute__('_discount')
38+
return price - (price * discount)
39+
return super().__getattribute__(name)
40+
41+
def __setattr__(self, name, value):
42+
if (name == 'price'):
43+
if type(value) is not float:
44+
raise ValueError('The "price" attribute must be a float')
45+
return super().__setattr__(name, value)
46+
47+
def __getattr__(self, name):
48+
return name + ' is not here!'
49+
50+
def __call__(self, title, author, price):
51+
self.title = title
52+
self.author = author
53+
self.price = price
54+
55+
56+
book1 = Book('Python Crash Course', 'Eric Matthes', 23.99)
57+
book2 = Book('Serious Python', 'Julien Danjou', 25.43)
58+
book3 = Book('Automate the Boring Stuff with Python', 'Al Sweigart ', 26.99)
59+
book4 = Book('Python for Kids', 'Jason Briggs', 19.79)
60+
61+
# print each object
62+
print(book1)
63+
print(book2)
64+
print(book3)
65+
print(book4)
66+
67+
# use str() and repr()
68+
print(str(book1))
69+
print(repr(book2))
70+
71+
# Check for equality
72+
print(book1 == book3)
73+
print(book1 == book2)
74+
print(book3 == book3)
75+
76+
# Check for greater and lesser value
77+
print(book2 >= book1)
78+
print(book2 < book1)
79+
print(book3 >= book2)
80+
81+
# Sorting books
82+
books = [book1, book3, book2, book4]
83+
books.sort()
84+
print([book.title for book in books])
85+
86+
# Try setting and accessing the price
87+
book1.price = 37.95
88+
print(book1)
89+
90+
book2.price = float(40) # using an int will raise an exception
91+
print(book2)
92+
93+
# If an attribute doesn't exist, __getattr__ will be called
94+
print(book1.randomprop)
95+
96+
# call the object as if it were a function
97+
print(book1)
98+
book1('Learning Python', 'Mark Lutz', 44.94)
99+
print(book1)

0 commit comments

Comments
 (0)