How to Write a Class in Python
Part 1 of 2:
Introduction to Classes
-
Open Python IDE. You can learn how to do this in Install Python.
- Use keyword
class
, followed by a space, the name of the class, and a colon.class Duck:
- Indent and add basic variables for class. To do this, press ↵ Enter or ⏎ Return. Indent and write out a basic variable followed by an equal sign, and then your variable surrounded in quotes.
class Duck: 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.
class Duck: says = "Quack" gender = "Male" name = "Richie" myDuck = Duck() # Create instance of Duck class what = 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.
class Duck: says = "Quack" gender = "Male" name = "Richie" def fly(): 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
class Duck: says = "Quack" gender = "Male" name = "Richie" def fly(): print('Duck flies') my_Duck = Duck() my_Duck.fly() # Will print "Duck flies"
- Change attributes of class.
class Duck: says = "Quack" gender = "Male" name = "Richie" def fly(): 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 (
self
explained below):
class Duck: def __init__(self): self.says = 'Quack' self.gender = "Male" self.name = "Richie" def fly(): 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
self
word 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:class Duck: def __init__(self): self.says = 'Quack' self.gender = "Male" self.name = "Richie" def fly(): 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:
class Duck: def __init__(self, says='Quack', gender='Male', name='Richie'): self.says = says self.gender = gender self.name = name def fly(): 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.
class Duck: def __init__(self, says='Quack', gender='Male', name='Richie'): self.says = says self.gender = gender self.name = name def fly(): 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" code 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"'''
Part 2 of 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:
def GCF(n, m): # Using the Euclidean Algorithm to find the greatest common factor while n: m, n = n, m % n return m def reduce_fraction(numerator, denominator): g = GCF(numerator, denominator) numerator //= g denominator //= g return numerator, denominator class Fraction: def __init__(self, numerator, denominator = 1): self.fraction = reduce_fraction(numerator, denominator) myFrac = Fraction(3, 4) # Fraction of 3/4, will not be reduced print(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:def GCF(n, m): # Using the Euclidean Algorithm to find the greatest common factor while n: m, n = n, m % n return m def reduce_fraction(numerator, denominator): g = GCF(numerator, denominator) numerator //= g denominator //= g return numerator, denominator class Fraction: def __init__(self, numerator, denominator = 1): self.fraction = reduce_fraction(numerator, denominator) def __str__(self): return str(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/2 print(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.
def GCF(n, m): # Using the Euclidean Algorithm to find the greatest common factor while n: m, n = n, m % n return m def reduce_fraction(numerator, denominator): g = GCF(numerator, denominator) numerator //= g denominator //= g return numerator, denominator def lcm(n, m): return n // GCF(n, m) # or m // GCF(n, m) def add_fractions(Frac1, Frac2): denom1 = Frac1[1] denom2 = Frac2[1] Frac1 = Frac1[0] * denom2 Frac2 = Frac2[0] * denom1 return reduce_fraction(Frac1+Frac2, denom1 * denom2) class Fraction: def __init__(self, numerator, denominator = 1): self.fraction = reduce_fraction(numerator, denominator) def __str__(self): return str(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): if isinstance(other_object, int): # if other_object is an integer return self + Fraction(other_object) # Make it of the Fraction class # (integers are just fractions with 1 as the denominator, after all!) if isinstance(other_object, Fraction): return add_fractions(self.fraction, other_object.fraction) else: raise TypeError("Not of class 'int' or class 'Fraction'") myFrac = Fraction(6, 4) # Fraction of 6/4, will be reduced to 3/2 other_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.
3.8 ★ | 16 Vote
You should read it
May be interested
- Code Python on the browser with these free online Python interpretersyou should use an interactive interactive shell. these are sites that allow you to write, execute python code and immediately see the results, without installing anything.
- Write a program to find the majority element in an array in Pythonin this article, tipsmake.com will learn with you how to write a program to determine the majority element in python programming language, write a program to find the majority element in an array in python
- Write a program to check password in Pythonyou can develop a strong password checker in python. here are details on how to write a password checker program in python.
- Write a program to print Pascal's Triangle in Pythonin this article, tipsmake.com will learn with you how to write a program to print pascal's triangle in python.
- Class Inheritance in Python (Part 2)in the previous part, i mentioned the basic properties of classes in python. in this part, i will mention the advanced properties and characteristics of classes.
- Module in Pythonin this python lesson we will know how to create and import a module in python. we will learn a few ways to import, using custom modules as well as python's built-in modules, please watch.
- Write a program to calculate the square root of a number in Pythonin this article, tipsmake.com will help you learn more about square roots and how to write a program to calculate square roots in python programming language.
- Write a program to find duplicate values in Pythonif you want to learn how to write a program to find duplicate values in python, this is the article for you.
- Write an alarm clock program in Pythonif you are new to python programming, writing an alarm program is a simple example for you to practice.
- More than 100 Python exercises have solutions (sample code)more than 100 python code examples are shared by guy zhiwehu on github, however, the solution of this series is written on the old python version. following tipsmake.com will be vietnameseized and edited to suit python 3.x to help you learn and practice python.