1 of 8

CSE 163

Classes and Objects

��Hunter Schafer

Questions During Class?

sli.do (Code: 163)

🎵Music: Still Woozy

2 of 8

This Time

  • Private
  • Warning: Default Parameters
  • os
  • Lambdas

Last Time

  • Objects (state and behavior)
  • References
  • Defining a class
  • Instantiate an object

2

3 of 8

Private

  • Python has no way to actually do this, but by convention people don’t access things that start with “_”

3

class Dog:

def __init__(self, name):

self._name = name

def bark(self):

print(self._name + ': Woof')

4 of 8

Default Parameters

  • You can use default parameters like you would before
  • You have to be careful when using objects as default values, it has some really bad unintentional side-effects

=

  • There is only one instance of the default parameter, they share a reference!

4

def append_to(element, to=[]):

to.append(element)

return to

my_list = append_to(12)

print(my_list)

my_other_list = append_to(42)

print(my_other_list)

5 of 8

Default Parameters Done Right

  • The fix is to not use an object as the default parameter, instead we usually use None

5

# Option 1

def append_to(element, to=None):

if to is None:

to = []

to.append(element)

return to

# Option 2

def append_to(element, to=None):

to = [] if to is None else to

to.append(element)

return to

6 of 8

os

  • os is a built-in package in Python that helps work with the computer (e.g. files)

6

import os

for file_name in os.listdir(directory_name):

print(file_name)

7 of 8

Lambdas

  • It’s kind of annoying to have to define a whole function just for this. It would be nice if there was a shorthand syntax

Introduce: Lambdas

7

def get_dog_name(d):

return d.get_name()

sorted(dogs, key=get_dog_name)

sorted(dogs, key=lambda d: d.get_name())

8 of 8

Group Work:

Best Practices

When you first working with this group:

  • Turn on your mic / camera or introduce yourself in chat
    • We prefer mic/camera if available to encourage sense of human interaction :)
  • Share your name + where in the world you’re calling in from!
  • Elect one person to “drive” and share their screen for reference

Tips:

  • Starts with making sure everyone agrees to work on the same problem
  • Make sure everyone gets a chance to contribute!
  • Ask if everyone agrees and periodically ask each other questions!
  • Call TAs over for help if you need any!

8