Python
/
Class
- 1 Language 9
-
Hello World
-
Variables
-
Functions
-
Conditional
-
Operators
-
While
-
Turtle
-
Script Mode
-
Debugging
- 2 Strings 6
-
Slice
-
Raw Strings
-
Regex
-
Validation
-
Config
-
Escape
- 3 Collections 5
-
Lists
-
Dictionaries
-
Efficiency
-
Tuples
-
References
- 4 Functions 5
-
Recursion
-
Factorial
-
Modulus
-
Reassignment
-
Approximate
- 5 Storage 8
-
Files
-
Databases
-
Pipes
-
With open
-
Shelve
-
Zip
-
Csv
-
Json
- 6 Class 4
-
Definition
-
Attributes
-
Functional
-
Methods
- 7 Goodies 5
-
Conditional Expression
-
List Comprehension
-
Generator
-
Named Tuple
-
Modules
- 8 Applications 5
-
Pythagora
-
Palindrome
-
Binary Search
-
Conway Game
-
Coin Flip
- 9 Scheduler 4
-
Time
-
Multithreading
-
Subprocess
-
Logging
- 10 Packages 2
-
Clipboard
-
Ocr
/
Methods
➟
➟
Last update: 19-11-2021
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 github Class