Object-Oriented Python: Types, Objects, and Methods
Authors
Python is an “Object-Oriented” Programming language. This means that data is transformed into code, an approach that makes Python very flexible.
In this session, you’ll learn to think about data in python in terms of “types”, which will open the doors for using a wide variety of tools in Python and make it easier to understand how to fix our code when Python raises an error message.
Section 1: One Approach to Coding: Code-Data Separation
| Code | Description |
|---|---|
round(x) |
Round x to the nearest whole number. |
pow(x, y) |
Raise x to the power of y. |
min(a, b, ...) |
Return the smallest of the input values. |
max(a, b, ...) |
Return the largest of the input values. |
sum(numbers) |
Return the sum of all elements in numbers. |
Function Syntax in Python
When you use a function in Python, first, you write the function name, then you pass the arguments to that function inside round brackets. Each argument is separated by a comma. Below are three examples of how a function can be used: one where the function takes no arguments, one where it takes a single argument, and one where it takes three arguments.
>>> function_name()
>>> function_name(argument1)
>>> function_name(argument1, argument2, argument3)Exercises
Answer the following questions using the built-in math functions round(), pow(), min(), max(), and sum()
Example: What is 7.8 rounded to the nearest whole number?
round(3.2)3Exercise: What is 7.8 rounded to the nearest whole number?
Solution
round(7.8)8Exercise: Which number is smaller: 4 or 5?
Solution
min(4, 5)4Exercise: Which number is bigger: 5, 8, or 10?
Solution
max([5, 8, 10])10Exercise: Which number is smaller:
- 80 divided by 4
- 3 times 7
Solution
min(80 / 4, 3 * 7)20.0Exercise: What’s the sum of four and five using the sum() function?
Solution
sum([4, 5])9Exercise: What’s the sum of the numbers one through five?
Solution
sum([1, 2, 3, 4, 5])
sum(range(1,6))15Section 2: Literal Data Syntax in Python
| Code | Description |
|---|---|
type(x) |
Return the type of x. |
Data in Python can take the form of many different types. The most basic are:
- int: 3 # whole numbers
- float: 3.1 # decimal numbers
- bool: True # the logical values, can only be True or False
- str: “hi” # text data
- bytes: b"hi123\x03" # a sequence of generic computer data
- NoneType: None # a placeholder, usually for missing values
Data can be “assigned” to variables for use in other lines of code using the equals sign:
>>> data = 3
>>> data + 5
8Sometimes it’s not clear what type of data a certain variable represents.
To find out the type of data, you can use the type() function:
>>> type(3)
int
>>> type('hello')
str
>>> type(data)
intExercises
Example: What type is 3?
type(3)intExercise: What type is -1?
Solution
type(-1)intExercise: What type is 5.2?
Solution
type(5.2)floatExercise: What type is data?
data = 3.14Solution
data = 3.14
type(data)floatExercise: What type is data?
data = 10Solution
type(data)intExercise: What type is data?
data = 10.Solution
data = 10.
type(data)floatExercise: What type is data?
data = FalseSolution
data = False
type(data)boolExercise: What type is data?
data = "The Weather"Solution
type(data)strExercise: What type is data?
data = NoneSolution
data = None
type(data)NoneTypeExercise: What type is data?
data = 5 > 2Solution
data = 5 > 2
type(data)boolExercise: What type is data?
data = round(3.2)
data3Solution
data = round(3.2)
type(data)intSection 3: Changing Types: Using Type Contructors to Make New Objects
| Code | Description |
|---|---|
int(x) |
Convert x to an integer (truncates decimals). |
float(x) |
Convert x to a float (decimal number). |
str(x) |
Convert x to a string (text representation). |
bool(x) |
Convert x to a boolean (True or False). |
bytes(x) |
Convert x to a bytes object. |
Just as how the function sum() transforms two numbers into a single number, functions can transform data found in one type into another type. Much of the time, this function is named the same as the type, so if you know the type’s name, you know how to make it.
For example, make a float from an int:
>>> x1 = 3
>>> type(x1)
int
>>> x2 = float(x1)
>>> x2
floatExercises
Example: Make data2 into a float, from data1.
data1 = 3
data2 = float(data1)
data2, type(data2)(3.0, float)Exercise: Make data2an int, from data1.
data1 = 10_000_000_000_000.000_000Solution
data1 = 10_000_000_000_000.000_000
data2 = int(data1)
data2, type(data2)(10000000000000, int)Exercise: Make data2 an int, from data1. (What’s different here from the round() function?)
data1 = 3.99Solution
data1 = 3.99
data2 = int(data1)
data2, type(data2)(3, int)Exercise: Make data2 a string, from data1. (What’s different here?)
data1 = 3.14000000Solution
data1 = 3.14000000
data2 = str(data1)
data2, type(data2)('3.14', str)Exercise: Turn data2 into a float, from data1.
data1 = "5.2"Solution
data1 = "5.2"
data2 = float(data1)
data2, type(data2)(5.2, float)Exercise: Turn data2 into an int from data1.
data1 = "5"Solution
data1 = "5"
data2 = int(data1)
data2, type(data2)(5, int)Exercise: Turn data2 into an int, from data1 (What happened?).
data1 = 5.2Solution
data1 = 5.2
data2 = int(data1)
data2, type(data2)(5, int)Exercise: Turn data2 into a string from data1. (Don’t worry if this one looks strange. What do you observe?)
data1 = b"testing"Solution
data1 = b"testing"
data2 = str(data1)
data2, type(data2), str(data1, 'utf8') # 'b' and quotes were included in the string("b'testing'", str, 'testing')Exercise: Turn data2 into a bytes from data1 (What’s interesting here?)
data1 = 5Solution
data1 = 5
data2 = bytes(data1)
data2 # made 5 empty bytesb'\x00\x00\x00\x00\x00'Section 4: Method Syntax in Python: Code and Data Aren’t Separate
| Code | Description |
|---|---|
dir(obj) |
List all methods and attributes of an object. |
obj.method_name() |
Call a method on an object using dot notation. |
__add__, __mul__, etc. |
Dunder methods that define operator behavior (e.g., +, *). |
'text'.count(substring) |
Example of a string method: count occurrences of a substring. |
+ operator |
Addition for numbers; concatenation for strings. |
* operator |
Multiplication for numbers; repetition for strings. |
Types in Python contain functions as well as data; when functions and data are combined, it’s called an “object”. Everything in Python is an object, which means that all data contains some useful functions that can be used. A function inside an object is called a “method”.
Methods in Python fall in two categories:
-
“Dunder” Methods: These methods are named with double-underscores in the beginning and end. They aren’t meant to be used directly, but rather tell Python which method to call when an operator is used. (For example, the
__add__method is called when the+operator is in the code) -
Normal Methods: These methods are meant to be used directly, by putting a
.after the object. (For example, strings can count the number of times a letter appears:'hello'.count('l'))
You can see what methods any object has by using the dir() function.
dir()usually produces a long list; usingprint()is a trick to make the whole list show up in the same line.
Exercises
Example: Print the list of methods that integers have. Do more methods start with an underscore or start with a letter?
dir(int)['__abs__',
'__add__',
'__and__',
'__bool__',
'__ceil__',
'__class__',
'__delattr__',
'__dir__',
'__divmod__',
'__doc__',
'__eq__',
'__float__',
'__floor__',
'__floordiv__',
'__format__',
'__ge__',
'__getattribute__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__index__',
'__init__',
'__init_subclass__',
'__int__',
'__invert__',
'__le__',
'__lshift__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__neg__',
'__new__',
'__or__',
'__pos__',
'__pow__',
'__radd__',
'__rand__',
'__rdivmod__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rfloordiv__',
'__rlshift__',
'__rmod__',
'__rmul__',
'__ror__',
'__round__',
'__rpow__',
'__rrshift__',
'__rshift__',
'__rsub__',
'__rtruediv__',
'__rxor__',
'__setattr__',
'__sizeof__',
'__str__',
'__sub__',
'__subclasshook__',
'__truediv__',
'__trunc__',
'__xor__',
'as_integer_ratio',
'bit_count',
'bit_length',
'conjugate',
'denominator',
'from_bytes',
'imag',
'is_integer',
'numerator',
'real',
'to_bytes']Exercise: Print the list of methods that None has. How many do not start with an underscore?
Solution
print(dir(None)) # None['__bool__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']Exercise: Print the list of methods that data has. How many do not start with an underscore? (You don’t need to actually count them, just get a rough idea.)
Solution
data = 'hi'
print(dir(data)) # lots['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']Exercise: Looking at the list of methods in dir(int), would you assume that you use the addition operator with integers?
Solution
'__add__' in dir(int)TrueExercise: Try it (3 + 2)
Solution
3 + 25Exercise: Try it using the method directly ((3).__add__(2)):
Solution
a = 3
a.__add__(2)5Exercise: Looking at the list of methods in dir(None), would you assume that you use the addition operator with None?
Solution
'__add__' in dir(None)FalseExercise: Looking at the list of methods in dir(str), would you assume that you use the addition operator with strings?
Solution
dir(str)['__add__',
'__class__',
'__contains__',
'__delattr__',
'__dir__',
'__doc__',
'__eq__',
'__format__',
'__ge__',
'__getattribute__',
'__getitem__',
'__getnewargs__',
'__getstate__',
'__gt__',
'__hash__',
'__init__',
'__init_subclass__',
'__iter__',
'__le__',
'__len__',
'__lt__',
'__mod__',
'__mul__',
'__ne__',
'__new__',
'__reduce__',
'__reduce_ex__',
'__repr__',
'__rmod__',
'__rmul__',
'__setattr__',
'__sizeof__',
'__str__',
'__subclasshook__',
'capitalize',
'casefold',
'center',
'count',
'encode',
'endswith',
'expandtabs',
'find',
'format',
'format_map',
'index',
'isalnum',
'isalpha',
'isascii',
'isdecimal',
'isdigit',
'isidentifier',
'islower',
'isnumeric',
'isprintable',
'isspace',
'istitle',
'isupper',
'join',
'ljust',
'lower',
'lstrip',
'maketrans',
'partition',
'removeprefix',
'removesuffix',
'replace',
'rfind',
'rindex',
'rjust',
'rpartition',
'rsplit',
'rstrip',
'split',
'splitlines',
'startswith',
'strip',
'swapcase',
'title',
'translate',
'upper',
'zfill']Exercise: Try it: 'Hello' + 'World'
Solution
"Hello" + "World"'HelloWorld'Exercise: Try it using the method directly ('Hello'.__add__('World')):
Solution
"Hello".__add__("World")'HelloWorld'Exercise: Looking at the list of methods in dir(float), would you assume that you use the multiplication operator with floats?
Solution
"__mul__" in dir(float)TrueExercise: Try it:
Solution
3.2 * 26.4Exercise: Try it using the method directly:
Solution
(3.2).__mul__(2)6.4Exercise: Looking at the list of methods in dir(str), would you assume that you use the multiplication operator with strings?
Solution
"__mul__" in dir(str)TrueExercise: Try it: 'GTC' * 10
Solution
"Hi" * 10'HiHiHiHiHiHiHiHiHiHi'Exercise: Try it using the method directly:
Solution
"Hi".__mul__(10)'HiHiHiHiHiHiHiHiHiHi'Section 5: Reviewing Terminology
Exercise: Is the following code an example of a used function, method, or operator?
sum([1, 2, 3])
Solution
# function"Hello".count('l')
Solution
# method3 + 5
Solution
# operatorimport math
math.sqrt(72)Solution
# function(72).__mul__(3)
# methodmul(72, 3)
# function