Table of Contents
This updated guide examines How to Write a Class in Python and organizes the essential facts, background, and practical takeaways in clear American English.
Part 1
Introduction to Classes

- Use keyword
class, followed by a space, the name of the class, and a colon.classDuck:
- Indent and add basic variables for class. To do this, press?Enteror?Return. Indent and write out a basic variable followed by an equal sign, and then your variable surrounded in quotes.
classDuck:says="Quack"gender="Male"name="Richie"
- Access the variables by creating instances of the class.
- In python, the dot notation is used to access methods and/or variables defined in the class.
- An example is shown below.
classDuck:says="Quack"gender="Male"name="Richie"myDuck=Duck()# Create instance of Duck classwhat=myDuck.says# Will access says variable of class Duck and# assign it to the variable "what"print(what)# Will print "Quack"
- Add functions to the class (these are called methods of the class).
- This is where the functionality of classes and their ability to store values can be seen.
classDuck:says="Quack"gender="Male"name="Richie"deffly():print('Duck flies') - Call the method of the class; in this case, Duck.
- Methods use the dot notation as well:
- Just like a normal function, use parenthesis to call the method of
myDuck
classDuck:says="Quack"gender="Male"name="Richie"deffly():print('Duck flies')my_Duck=Duck()my_Duck.fly()# Will print "Duck flies" - Change attributes of class.
classDuck:says="Quack"gender="Male"name="Richie"deffly():print('Duck flies')my_Duck=Duck()my_Duck.gender="Female"# Changes value of variable gender in my_Duck# Now, printing my_Duck.gender will output "Female" - Initialize the Class. Classes run an initializing function every time the programmer creates an instance of that class.
- To create this function, add a few spaces between the first and second lines of the class and type
def __init__(self):on the second line (make sure to indent). - In the Duck example (
selfexplained below):
classDuck:def__init__(self):self.says='Quack'self.gender="Male"self.name="Richie"deffly():print('Duck flies')my_Duck=Duck()# You can still get the variables the same way, but now# they are wrapped in a function - later they will be changed# by other functions in class Duck.The
selfword is the instance of the Duck class that is being created. This word can be whatever the programmer wishes as long as it is the first argument of the__init__function. - To create this function, add a few spaces between the first and second lines of the class and type
- Add Default Arguments to
__init__function. A class that does not take arguments of any kind is clunky. First, type this into the python console after the class definition:classDuck:def__init__(self):self.says='Quack'self.gender="Male"self.name="Richie"deffly():print('Duck flies')my_Duck=Duck()my_Duck.says='I don't want to quack'my_Duck.gender="Female"my_Duck.name='Lizz'new_Duck=Duck()new_Duck.name='Dude'new_Duck.says="IDK"There is a much better way to do the same process - in one line. This will require a little manipulation of the Duck class:
classDuck:def__init__(self,says='Quack',gender='Male',name='Richie'):self.says=saysself.gender=genderself.name=namedeffly():print('Duck flies')Let's delve into this example, beginning with the arguments:
says='Quack', gender='Male', name='Richie'- these are default arguments - if the programmer inputs something else into the function, the argument will take that value instead. If the programmer doesn't input anything, the argument takes on the value assigned to it by the = operator.- Finally, the variables are added to the instance of the class that is created when the programmer calls the class method.
- Create Instances of Class with Default Variables. For this example, we will re-create the two previous Ducks - my_Duck and new_Duck.
classDuck:def__init__(self,says='Quack',gender='Male',name='Richie'):self.says=saysself.gender=genderself.name=namedeffly():print('Duck flies')my_Duck=Duck('I don't want to quack','Female','Lizz')new_Duck=Duck('IDK',name='Dude')# or new_Duck = Duck('IDK', 'Male', 'Dude')''' Previous "chunky" codemy_Duck = Duck()my_Duck.says = 'I don't want to quack'my_Duck.gender = "Female"my_Duck.name = 'Lizz'new_Duck = Duck()new_Duck.name = 'Dude'new_Duck.says = "IDK"'''
Part 2
Advanced Numerical Classes
- Begin the Class. This was discussed in Part 1 of this article. For our example, we will write a fraction class:
defGCF(n,m):# Using the Euclidean Algorithm to find the greatest common factorwhilen:m,n=n,m%nreturnmdefreduce_fraction(numerator,denominator):g=GCF(numerator,denominator)numerator//=gdenominator//=greturnnumerator,denominatorclassFraction:def__init__(self,numerator,denominator=1):self.fraction=reduce_fraction(numerator,denominator)myFrac=Fraction(3,4)# Fraction of 3/4, will not be reducedprint(myFrac)
Output:
- Overwrite the __str__ and __repr__ methods. These two methods control how the instances of the class are displayed using the print function. A good programmer wants the fraction displayed when he/she types in
print(myFrac). Thus the following addition is made:defGCF(n,m):# Using the Euclidean Algorithm to find the greatest common factorwhilen:m,n=n,m%nreturnmdefreduce_fraction(numerator,denominator):g=GCF(numerator,denominator)numerator//=gdenominator//=greturnnumerator,denominatorclassFraction:def__init__(self,numerator,denominator=1):self.fraction=reduce_fraction(numerator,denominator)def__str__(self):returnstr(self.fraction[0])+'/'+str(self.fraction[1])__repr__=__str__# Assign one function to another.# This is legal in python. We just renamed# __str__ with __repr__myFrac=Fraction(6,4)# Fraction of 6/4, will be reduced to 3/2print(myFrac)
Output:
3/2
- Add Functionality. Please refer to the Official Python Docs for a complete list of operators that can be written as functions. For the Fraction class example, we will extend the class with an addition function. The two functions that need to be written to add classes together are the __add__ and __radd__ functions.
defGCF(n,m):# Using the Euclidean Algorithm to find the greatest common factorwhilen:m,n=n,m%nreturnmdefreduce_fraction(numerator,denominator):g=GCF(numerator,denominator)numerator//=gdenominator//=greturnnumerator,denominatordeflcm(n,m):returnn//GCF(n,m)# or m // GCF(n, m)defadd_fractions(Frac1,Frac2):denom1=Frac1[1]denom2=Frac2[1]Frac1=Frac1[0]*denom2Frac2=Frac2[0]*denom1returnreduce_fraction(Frac1+Frac2,denom1*denom2)classFraction:def__init__(self,numerator,denominator=1):self.fraction=reduce_fraction(numerator,denominator)def__str__(self):returnstr(self.fraction[0])+'/'+str(self.fraction[1])__repr__=__str__# Assign one function to another.# This is legal in python. We just renamed# __str__ with __repr__def__add__(self,other_object):ifisinstance(other_object,int):# if other_object is an integerreturnself+Fraction(other_object)# Make it of the Fraction class# (integers are just fractions with 1 as the denominator, after all!)ifisinstance(other_object,Fraction):returnadd_fractions(self.fraction,other_object.fraction)else:raiseTypeError("Not of class 'int' or class 'Fraction'")myFrac=Fraction(6,4)# Fraction of 6/4, will be reduced to 3/2other_Frac=Fraction(2,3)print(myFrac+other_Frac,'n')print(myFrac+2)Output:
13/6 7/2
- Continue Looking Around. This article has just scratched the surface on what classes can do. Another great resource for any questions is Stack OverFlow. For a challenge, go to Think Functional and write the classes.
FAQ
What is How to Write a Class in Python about?
It provides a structured overview of class, explains the main context, and highlights practical takeaways for readers.
Why does this topic matter?
Understanding the main concepts helps readers evaluate the issue, avoid common mistakes, and make better-informed decisions.
How should readers use this information?
Use the guidance as a practical starting point, confirm details that may have changed, and follow current product, safety, or security recommendations.
Reader Comments 0
Sign in with email or Google to join the discussion.