93. Classes¶
You are already familiar with defining your own functions, like this:
[1]:
def f(a):
return a
[2]:
f(2)
[2]:
2
But what about defining your own types? First, lets remind ourselves of some built-in types:
[3]:
a = 2
[4]:
type(a)
[4]:
int
OK, so there is a thing called an int
.
[5]:
int
[5]:
int
We can make a new int
by calling the type name as a function:
[6]:
int()
[6]:
0
To build our own type, we can use the class
keyword:
[7]:
class MyClass:
pass
[8]:
MyClass
[8]:
__main__.MyClass
[9]:
instance = MyClass()
[10]:
type(instance)
[10]:
__main__.MyClass
93.1. What is this good for?¶
The essence of object-oriented programming is allowing for data and algorithms to be combined in one place. Functions allow us to re-use algorithms, but classes allow us to combine them with local data:
[11]:
class MyClass2:
def __init__(self, name):
print("I'm in __init__!")
self.name = name
def say_my_name(self):
print(self.name)
[12]:
s = MyClass2('Carl')
I'm in __init__!
[13]:
s.say_my_name()
Carl
93.2. Objects must be “like” things¶
[14]:
class Person:
def __init__(self, name):
self.name = name
def display_name(self):
print(self.name)
[15]:
carl = Person("Carl Sandrock")
[16]:
carl.display_name()
Carl Sandrock
[ ]: