If coding tutorials with math examples are the bane of your existence, keep reading. This series uses relatable examples like dogs and cats.
Classes and Methods
# syntax
class ClassName:
pass # remember, pass just means there is not code here yet
Creating a Class
A class is basically a template for an object. Let's create a class (template) for dog.
class Dog: # the name of our template/class
def __init__ (self, name, color): # initialize attributes
self.name = name
self.color = color
Creating an Object
Having a template/class for Dog
is great, but it's useless if we don't actually use it. Let's create a dog object.
d = Dog('Cheeto', 'tan')
print(d.name)
Cheeto
Class Constructor
Constructors are each of the attributes of the class. In this case, we already have name
and color
. You could also add age
and many other things.
class Dog: # the name of our template/class
def __init__ (self, name, color, age): # initialize attributes
self.name = name
self.color = color
self.age = age
Object Methods
Objects can have methods. Think of objects as nounds and methods as actions or verbs.
class Dog: # the name of our template/class
def __init__ (self, name, color, age): # initialize attributes
self.name = name
self.color = color
self.age = age
def dog_info(self):
return f'{self.name} is {self.age}.'
d = Dog('Cheeto','tan and black','5')
print(d.dog_info())
Cheeto is 5.
Object Default Methods
Sometimes, you may want to have default values. The default values will fill in all the info, but can also be overridden.
class Dog: # the name of our template/class
def __init__ (self, name = "Cheeto", color = "tan and black", age = "5"): # initialize attributes
self.name = name
self.color = color
self.age = age
def dog_info(self):
return f'{self.name} is {self.age} and {self.color}.'
d1 = Dog()
print(d1.dog_info())
d2 = Dog('Wiley','brown, black, and white','age unknown')
print(d2.dog_info())
Cheeto is 5 and tan and black.
Wiley is age unknown and brown, black, and white.
Series loosely based on
Top comments (0)