DEV Community

Vicki Langer
Vicki Langer

Posted on

Charming the Python: Classes & Methods pt 1

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

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.
Enter fullscreen mode Exit fullscreen mode

Series loosely based on

Top comments (0)