1 of 9

CSE 163

More Objects�

Suh Young Choi�

🎶 Listening to: David Garrett

💬 Before Class: Are animals better when they’re orbular or angular (aesthetically)?

2 of 9

Last Time + This Time

Last Time

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

This Time

  • Private fields and methods
  • Default parameters

2

3 of 9

Updates

  • THA 3 Peer Reviews due tonight!

  • Checkpoint 3 out now; due Monday!

  • Proposal or Vision Statement due tomorrow night!
    • What questions do you have about either of these?

3

4 of 9

Private

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

4

class Dog:

def __init__(self, name: str) -> None:

self._name: str = name

def bark(self) -> None:

print(self._name + ': Woof')

5 of 9

Private fields and methods

  • Both fields and methods can be private if you don’t want them accessed or changed by your user
  • Private methods are often helper functions that your user doesn’t actually need

5

class SpiderFolk:

def __init__(self, name: str) -> None:

self._name: str = name

def _secret_identity(self) -> str:

if ‘spider’ not in self._name.lower():

return “Spider-Man!”

else:

return “who?”

def get_me_pictures(self, count: int) -> None:

print(f’{count} pictures of {self._secret_identity()}’)

6 of 9

“Getter” vs. “Setter” methods

  • Two broad categories of class functions that involve field manipulation
  • “Getter” methods return certain values, like fields or quick manipulations
  • “Setter” methods update fields or create new values

6

class SpiderFolk:

def __init__(self, name: str) -> None:

self._name: str = name

def get_name(self) -> str:

return self._name # a getter method

def rename(self, new_name: str) -> None:

self._name = new_name + “(renamed)” # a setter method

7 of 9

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
    • In other words, they share a reference!

7

def append_to(element: int,

to: list[int] = []) -> list[int]:

to.append(element)

return to

my_list = append_to(12)

print(my_list)

my_other_list = append_to(42)

print(my_other_list)

8 of 9

Default Parameters Done Right

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

8

# Option 1

def append_to(element: int,

to: list[int] | None = None) -> list[int]:

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

9 of 9

Next Time + Before Next Time

Next Time

  • Magic methods
  • Lambda functions
  • Networks

Before Next Time

  • THA 3 Peer Reviews due tonight
  • Go to section!
  • Turn in Vision Statement or Proposal!

9