Objects and Methods
Objects and Methods
- What's an object? →
- What's a method? →
Objects
- object - a thing that a variable name can refer to
- all of the values in Python are things
- "hello" is a str object, 42 is an int object
- an object can have attributes …data associated with an object
- an object can have methods …actions that the object can perform
Methods
- a method is essentially a function that's associated with a particular object
- you can call a method just like a function… but you have to use the dot operator
- object.method() - it's similar to using a method in a module!
- for example: leo.forward(200)
- …means I'm calling the forward() function on an object called leo (turns out, that's a turtle object)
Examples of Objects
What are some objects we've seen?
- essentially, all data that we've seen is an object!
- int
- float
- str
- Turtle
- Screen
- etc
Objects vs Types
Aren't those just types? Yes! But to be more specific:
- a type is a classification of data
- an object is the data itself, referred to by a variable name
- an object is an instance of a type or class
- saying "xxxxx objects" (a kind or type of object) and "types" are interchangeable
Examples of Objects
What are some methods we've seen (for Turtle, str and list objects?)
- Turtle
- forward(int)
- up()
- left(int)
- etc.
- str
- find(str)
- upper()
- isalpha()
- isdigit()
- etc.
- list
- append(object)
- pop()
- etc.
Methods vs Functions
Aren't those just functions? Yes! Well, sort of:
- a method is a function within the context of an object
- a method is called on an object, so to call it, you must have an object around!
- use the object's name, the dot operator, and then call the method like you would a function
- sometimes methods mutate the original object
- so far, we've only seen this behavior in lists (append, sort, etc.)
- otherwise, they may return a value (or both mutate and return a value, such as pop)