Skip to content

How to define a class in Python

For this example we will be generating a type called “Animal”

class Animal(object):

Class = We’re defining a class

Animal = We are naming our class

(object) =  We are telling the class what to inherit from, in this case we are inheriting from the Python ‘object’, which is the lowest level typeinside of python.

This means that ‘Animal’ will take all of the traits that ‘object’ has, might be handy to use sass as an example of how this works, consider this:

.object {
  color: blue;
  font-size: 12pt;
  width: 300px;
}

.animal {
  @extend .animal;
}

Where animal will extend object.

Within a class we can define methods, these are similar to functions but they have to live inside of a class and they all take selfas a first argument, lets create 3 methods within our Animal class:

class Animal(object):

	def speak(self):
		print "I don’t know how to speak"
	
	def walk(self):
		print "I don’t know how to walk"
	
	def breath(self):
print "I don’t know how to breath"

Other than living within a class and taking self as the first argument they are the same as functions.

Published inPyCharmPythonscripting