Python 3home |
Introduction to Python
davidbpython.com
A class is a definition for a custom type of object.
At the start of this course, we defined an object:
An object is: --> a unit of data --> of a particular type --> with type-specific functionality
All objects have behaviors called methods and data stored in attributes.
mylist = [1, 2, 3]
mylist.append(4) # list, [1, 2, 3, 4]
print(mylist[-1]) # int, 4
mystr = 'hello'
ustr = mystr.upper() # str, 'HELLO'
myint = 5
dblint = myint + 5 # int, 10
Consider any object you encounter in terms of its data and behaviors.
from datetime import date, timedelta
dt = date(2023, 12, 30) # new 'date' object for 12/30/2023
td = timedelta(days=3) # new 'timedelta' object: 3 day interval
dt2 = dt + td # new date object: date + timedelta
print(dt) # 2024-01-02 (3 days later)
print(type(dt)) # <class 'datetime.datetime'>
When creating a new object type, consider what you want it to be and to do.
import sysadmin # theoretical / proposed module
s1 = sysadmin.Server('work1',
username='user',
password='pass')
ms = s1.ping()
print(f'{s1.hostname} pinged at {ms}ms') # 'work1' pinged at 43ms
s1.copyfile_up('myfile.txt') # copies a file up to the server
s1.copyfile_down('yourfile.txt') # copies a file down from the server
print(s1.uptime()) # 7920 ('work1' restarted 2 hours, 12 minutes ago)
s1.restart() # restarts the server
print(s1.uptime()) # 2 (work1 restarted 2 seconds ago)
The class block statement is the blueprint for an object type.
class Me:
pass # 'pass' marks an empty block
m = Me() # construct a new 'Me' object
print(type(m)) # <class '__main__.Me'>
Ex. 13.1
A method is a function that is part of a class.
class Say:
def greet(self):
print('Hello!')
def make_greeting(self, name):
return f'Hello, {name}!'
s = Say()
s.greet() # Hello!
g = s.make_greeting('Guido') # 'Hello, Guido!'
13.2 - 13.2