Python
/
Class
- 1 Language 9
-
Hello World S
-
Variables S
-
Functions S
-
Conditional A S
-
Operators S
-
While S
-
Turtle S
-
Script Mode S
-
Debugging S
- 2 Strings 7
-
Slice S
-
Raw Strings S
-
Regex A S
-
Validation S
-
Config S
-
Security S
-
Encrypt A S
- 3 Collections 5
-
Lists S
-
Dictionaries S
-
Efficiency S
-
Tuples S
-
References S
- 4 Functions 5
-
Recursion S
-
Factorial S
-
Modulus S
-
Reassignment S
-
Approximate S
- 5 Storage 8
-
Files S
-
Databases S
-
Pipes S
-
With open S
-
Shelve A S
-
Zip S
-
Csv S
-
Json S
- 6 Class 4
-
Definition S
-
Attributes S
-
Functional S
-
Methods S
- 7 Goodies 5
-
Conditional Expression S
-
List Comprehension S
-
Generator S
-
Named Tuple S
-
Modules S
- 8 Applications 5
-
Pythagora A S
-
Palindrome A S
-
Binary Search A S
-
Conway Game A S
-
Coin Flip A S
- 9 Scheduler 4
-
Time S
-
Multithreading A S
-
Subprocess S
-
Logging S
- 10 Packages 6
-
Clipboard A S
-
Ocr A S
-
Socket S
-
Image S
-
Virtualenv S
-
Jupyter S
S
R
Q
Python Class Methods
In OOP, the objects are the active agents Hey object, print yourself!
Methods
p288 Methods are the same as functions but defined inside the class.
# Methods are functions defined inside a class
class Time:
def print(self):
print('%.2d:%.2d:%.2d' %
(self.hour, self.minute, self.second)
)
start = Time()
start.hour = 9
start.minute = 45
start.second = 0
# Invoking a method is different from calling a function
Time.print(start) # 09:45:00
Active
p291 In OOP, the objects are the active agents.
# In functional programming, the function is the active agent:
# Hey print_time! Here's an object to print
#
# In OOP, the objects are the active agents.
# Hey obj start! Please print yourself
class Time:
def set(self, seconds):
time = Time()
minutes, time.seconds = divmod(seconds, 60)
hour, time.minutes = divmod(minutes, 60)
time.hour = hour
return time
def print(self):
print('%.2d:%.2d:%.2d' %
(self.hour, self.minutes, self.seconds)
)
time = Time()
time.set(160).print() # 00:02:40
Special methods
p293 Method __init__ gets invoked when an object is instantiated.
# Method __init__ gets invoked when an object is instantiated
# Method __str__ returns a string representation of an object
class Time:
def __init__(self, hour=0, min=0, sec=0):
self.hour = hour
self.min = min
self.sec = sec
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.min, self.sec)
time = Time(9, 30)
print(time) # 09:30:00
➥ Questions
Last update: 2 days ago