1 of 7

CSE 163

Classes and Objects

��Hunter Schafer

💬 Before Class: What is your least favorite root vegetable?

🎵Music: Glass Animals

2 of 7

This Time

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

Last Time

  • Categorical Features
  • Assessing Performance
  • Overfitting
  • Model Complexity
    • Hyperparameters

2

3 of 7

Objects

  • An object holds state and provides behaviors that operates on that state
  • Each object has its own state
  • Example: DataFrame

3

a

0

1

1

2

2

3

df1 = pd.read_csv('file1.csv')

df2 = pd.read_csv('file2.csv')

df1.loc[1, 'a'] # 2

b

0

4

1

5

2

6

df1

df2

4 of 7

Class

  • A class lets you define a new object type by specifying what state and behaviors it has
  • A class is a blueprint that we use to construct instances of the object

Here is a full class

4

class Dog:

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

self.name: str = name

def bark(self) -> None:

print(self.name + ': Woof')

A class definition

An initializer that sets fields (state)

A method (behavior)

5 of 7

Building Dogs

5

d1 = Dog('Chester')

d2 = Dog('Scout')

d3 = d1

d1.bark()

d2.bark()

d3.bark()

d1

name: 'Chester'

d2

name: 'Scout'

d3

# Chester: Woof

# Scout: Woof

# Chester: Woof

6 of 7

Note to Self

  • In the Dog example, every method (initializer or otherwise) takes a parameter called “self”
  • This indicates which instance the method is being called on

  • On the first line, self references Chester
  • On the second line, self references Scout
  • On the third line, self references Chester

6

class Dog:

def __init__(self, name):

self.name = name

def bark(self):

print(self.name + ': Woof')

d1 = Dog('Chester')

d2 = Dog('Scout')

d3 = d1

d1.bark()

d2.bark()

d3.bark()

7 of 7

Group Work:

Best Practices

When you first working with this group:

  • Introduce yourself!
  • If possible, angle one of your screens so that everyone can discuss together

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!

7