Skip to content

Commit bbdd532

Browse files
committed
OOP
1 parent 7232dee commit bbdd532

2 files changed

Lines changed: 283 additions & 0 deletions

File tree

‎python/08-oop-basics.py‎

Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
2+
########## Create a Class and __init__ ##########
3+
4+
5+
#This section is designed to be a simple introduction to object oriented programming
6+
#We are in no way covering everything...
7+
#Probably will do OOP or intermediate Python series dedicated to this stuff
8+
9+
class Book():
10+
pass
11+
12+
book = Book()
13+
print(book)
14+
15+
#When we say Book() we are instantiating a new object
16+
#This object iws assigned to the book variable
17+
#Printing it gives us the type and memory location
18+
#You can also get the type:
19+
20+
print(type(book))
21+
22+
#We can check type like so:
23+
24+
if isinstance(book, Book):
25+
print("It is indeed book. Read it")
26+
else:
27+
print("nope, not a book")
28+
29+
#We can use the class to make numerous books:
30+
book2 = Book()
31+
#Consider the class as the cookie cutter to make numerous cookies.
32+
33+
#We can add attributes to any object dynamically like so:
34+
book.title = "Goodnight Moon"
35+
print(book.title)
36+
37+
#This is cool and all but every book has a title, so we can make it part of the structure
38+
#This requires a bit more syntax...
39+
#also notice that you can override any class as we go.
40+
class Book():
41+
def __init__(self, title):
42+
self.title = title
43+
44+
#consider this the constructor, or the function that is invoked when we create a book.
45+
#self refers to the book being created and we don't have to worry about passing that, it's implicit
46+
#Title is passed in as an argument, and assigned to self.title (the title of the book)
47+
#We will explore this in more detail in a video soon.
48+
49+
#We then pass a title to the Book as we create it:
50+
book = Book("Goodnight Moon Again")
51+
book2 = Book("Are You My Mother")
52+
print(book.title)
53+
print(book2.title)
54+
55+
#This will now fail as title is required :)
56+
#book3 = Book()
57+
58+
#If you want the title to be optional you can give it a default (either a value or None):
59+
60+
class Book():
61+
def __init__(self, title=None):
62+
self.title = title
63+
64+
book = Book()
65+
print(book.title) #Still exists just no value.
66+
67+
#This fails as .test doesn't exist.
68+
#print(book.test)
69+
70+
#Next up we are going to create methods in our class.
71+
72+
73+
########## Methods ##########
74+
75+
76+
#A method is just a function on an object.
77+
#We can define any functions to be attached to our objects by putting em in our class
78+
#We just have to have the implicit parameter self
79+
80+
class Book():
81+
def __init__(self, title, pages):
82+
self.title = title
83+
self.pages = pages
84+
85+
def log(self):
86+
print(f"{self.title} is {self.pages} pages long")
87+
88+
def is_short(self):
89+
if self.pages < 100:
90+
return true
91+
92+
book = Book("Are You My Mother?", 100)
93+
book.log() #no need to pass anything to self parameter.
94+
95+
#A note on __init__
96+
#__init__ is also a method, but it's special in that it is invoked automatically
97+
#When we create an object.
98+
#There are a lot of methods with a similar naming structure we are going to see.
99+
#__eq__, __hash__, __str__, etc.
100+
101+
if book.is_short():
102+
#do something
103+
print("read book")
104+
else:
105+
print("Aint got time for that")
106+
107+
#Next up I want to explain this self parameter we've been seeing
108+
109+
#Without methods, we would have to create functions like this:
110+
111+
def book_is_short(book):
112+
if book.pages < 100:
113+
return true
114+
115+
if book_is_short(book):
116+
#do something
117+
print("read book")
118+
else:
119+
print("Aint got time for that")
120+
121+
#Which would work but not ideal as we'd easily be overwhelemed with so many functions
122+
#And no organization. It's ideally attached to the object as it's related to the object.
123+
124+
125+
########## Class Level Variables ##########
126+
127+
128+
#We're going to talk about class variables.
129+
#Coming from another language, this would be the closest thing to "static" members
130+
#First, we need to understand self.
131+
132+
#self refers to the object things are being invoked on,
133+
#When we create an object. __init__ assigns stuff to self
134+
#That allows each object to have attributes.
135+
136+
#Any time we create a method, we have self as a parameter.
137+
#This means the method is attached to each object.
138+
139+
#if we leave off self, we are creating it at the class level, which is shared for all objects
140+
141+
142+
class Book():
143+
favs = [] #class
144+
145+
def __init__(self, title, pages):
146+
self.title = title
147+
self.pages = pages
148+
149+
def log(self):
150+
print(f"{self.title} is {self.pages} pages long")
151+
152+
def is_short(self):
153+
if self.pages < 100:
154+
return true
155+
156+
157+
book = Book("Are You My Mother?", 100)
158+
book2 = Book("The Digging-est Dog", 72)
159+
160+
Book.favs.append(book)
161+
Book.favs.append(book2)
162+
163+
print(Book.favs) #Favs is related to books, but not tied to one individual book
164+
#We use self as a parameter if it's unique to each object :)
165+
166+
167+
########## __str__ ##########
168+
########## __eq__ ##########
169+
########## __hash__ and Collections ##########
170+
171+
172+
#To save save space we are combing the code for all three of these sections.
173+
174+
class Book():
175+
favs = [] #class
176+
177+
def __init__(self, title, pages):
178+
self.title = title
179+
self.pages = pages
180+
181+
def is_short(self):
182+
if self.pages < 100:
183+
return true
184+
185+
#What happens when you pass object to print?
186+
def __str__(self):
187+
return f"{self.title}, {self.pages} pages long"
188+
189+
#What happens when you use ==?
190+
def __eq__(self, other):
191+
if(self.title == other.title and self.pages == other.pages):
192+
return True
193+
194+
#It's approriate to give something for __hash__ when you override __eq__
195+
# #This is the recommended way if mutable (like it is here):
196+
__hash__ = None
197+
198+
#If should immutable, you could do something like this.
199+
#This replaces __hash__ = None
200+
def __hash__(self):
201+
return hash(self.title) ^ hash(self.pages) #xor with hash of attributes
202+
#from Mastering Object-Oriented Python
203+
204+
book = Book("Are You My Mother", 100)
205+
print(book)
206+
equal_book = Book("Are You My Mother", 100)
207+
print("Are they considered equal?", book == equal_book) #yep
208+
print("Are they the same object?", book is equal_book) #nope
209+
book2 = Book("The Digging-est Dog", 72)
210+
211+
print(hash(book), hash(book2))
212+
213+
print("old hash", hash(book))
214+
book.title = "new"
215+
print("new hash", hash(book)) #BAD!!!
216+
#Hashes shouldn't change

‎python/09-objects-io.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
class Book():
2+
favs = [] #class
3+
4+
def __init__(self, title, pages):
5+
self.title = title
6+
self.pages = pages
7+
8+
def is_short(self):
9+
if self.pages < 100:
10+
return true
11+
12+
#What happens when you pass object to print?
13+
def __str__(self):
14+
return f"{self.title}, {self.pages} pages long"
15+
16+
#What happens when you use ==?
17+
def __eq__(self, other):
18+
if(self.title == other.title and self.pages == other.pages):
19+
return True
20+
21+
#It's approriate to give something for __hash__ when you override __eq__
22+
# #This is the recommended way if mutable (like it is here):
23+
__hash__ = None
24+
25+
26+
########## Passing by Object Reference ##########
27+
28+
29+
book = Book("Where Is My Mother?", 100)
30+
print(book)
31+
32+
def modify(book):
33+
book.title = "Changed noob"
34+
35+
modify(book)
36+
print(book)
37+
38+
#What is we print id to follow?
39+
40+
def modify(book):
41+
print(id(book))
42+
book.title = "Changed noob"
43+
print(id(book))
44+
45+
print(id(book))
46+
modify(book)
47+
print(id(book))
48+
49+
#We get the same number for everything
50+
51+
book = Book("Are You My Mother?", 100)
52+
print("let's reassign")
53+
def modify(book):
54+
print(id(book))
55+
book = Book("Changed noob", 100)
56+
print(id(book)) #This is a different id.
57+
#The original is unchanged. Reassigning
58+
59+
print(id(book))
60+
modify(book)
61+
print(id(book))
62+
print(book) #Stayed the same!
63+
64+
65+
########## Reading from a file ##########
66+
########## Context manager (as?) ##########
67+
########## Intro to Exception handling ##########

0 commit comments

Comments
 (0)