Jed Rembold & Fred Agbo
March 15, 2024
What would be the output of the printed statement in the code to the right?
(1, 'a', 'b')
(1, 'a')
A = (1, 3, 5)
B = (2*A, ('a', ) )
C = B + ('b', 'c', 'd')
D = tuple()
for v in C[:3]:
D += v[:1]
print(D)
GRect
class.
GRect
classClass definitions in Python start with a header line consisting
of the keyword class
and then the class
name
The body of the class will later contain definitions, but initially can just leave blank
pass
keywordclass Employee:
"""This class is currently empty!"""
Once the class is defined, you can create an object of this class type by calling the class as if it were a function:
clerk = Employee()
You can select an attribute from an object by writing out the object name, followed by a dot and then the attribute name.
As an example
clerk.name
would select the name
attribute for the
clerk
object
Attributes are assignable, so
clerk.salary *= 2
would double the clerk’s current salary
You can create a new attribute in Python by simply assigning a name and a value, just like you’d define a new variable
We could, for instance, create a
clerk
in the following fashion:
def create_clerk():
clerk = Employee()
clerk.name = "Bob Cratchit"
clerk.title = "clerk"
clerk.salary = 15
return clerk
Note that none of these assigned attributes affect the
Employee
class in any way
We could accomplish this more generally by passing arguments to our function:
def create_employee(name, title, salary):
emp = Employee()
emp.name = name
emp.title = title
emp.salary = salary
return emp
We could then use that as:
clerk = create_employee('Bob Cratchit', 'clerk', 15)
boss = create_employee(
'Ebeneezer Scrooge', 'founder', 1000
)