How to Create a Class in Python - dummies

By John Paul Mueller

Python allows you to make an interesting class of your own. In this case, you create a class that you place into an external module and eventually access within an application. Here is the code that you need to create the class.

class MyClass:
 def __init__(self, Name="Sam", Age=32):
  self.Name = Name
  self.Age = Age
 def GetName(self):
  return self.Name
 def SetName(self, Name):
  self.Name = Name
 def GetAge(self):
  return self.Age
 def SetAge(self, Age):
  self.Age = Age
 def __str__(self):
  return "{0} is aged {1}.".format(self.Name,

In this case, the class begins by creating an object with two instance variables: Name and Age. If the user fails to provide these values, they default to Sam and 32.

This example provides you with a new class feature. Most developers call this feature an accessor. Essentially, it provides access to an underlying value. There are two types of accessors: getters and setters. Both GetName() and GetAge() are getters.

They provide read-only access to the underlying value. The SetName() and SetAge() methods are setters, which provide write-only access to the underlying value. Using a combination of methods like this allows you to check inputs for correct type and range, as well as verify that the caller has permission to view the information.

As with just about every other class you create, you need to define the __str__() method if you want the user to be able to print the object. In this case, the class provides formatted output that lists both of the instance variables.