Python Tutorial: Classes, Objects, Methods, init and Simple Examples
Python Tutorial on Classes, Objects, Methods: In this post we will dive into Python classes, methods, objects and using the init constructer to initialize classes. Object oriented programming has gone well past being a fad (sorry punchcards) like it or not encapsulation and inheritance is winning out. The idea is to make modules and procedures abstracted, modifiable and reusable without needing to worry about reinventing the wheel. All interesting stuff, but this is just to give some examples as I am knocking off years of rust and having some fun with Python. These are just simple examples that might help folks out as they start learning programming. Most attempts Python tutorials on classes object methods etc, are more advanced than are appropriate for beginners.
If you want a quick review on basic functions check this tutorial.
- More Python tutorials: Functions and Passing Lists and Dictionaries with Simple Examples
Python Classes and Object Oriented Programming OOB
If you look at python.org docs the definition is about as clear as mud. No offense intended, programming concepts in general can fairly nacient and wide open to interpretation regardless of language since it is as much style and theory. I tend to explain classes and methods (think function in a class) as a blueprint for what to pass and object data with attributes being applied through a framework. I can pass an object (examples to follow) into a class and it modifies the object based on the blueprint.
Python Methods
In the simplest term a method is a function inside of an object. You can pass attributes (variable inside a method) to the class and method that will get processed inside of the method and independently for each object. Variables or attributes defined or initialized at the beginning of the class are inherited to the methods inside that class. We will see in the examples.
Python Self for OOB
This can be rather confusing starting out. In a method which is a function inside of a class the first parameter is always self. Self is just referring to the object you passed into the method. Clear as mud? One other thing is a class object can be called or instantiated using __init__ (self). Using init will save you a couple lines of code. I learn through example so enough chit chat.
Practical Application (ever so loosely o_O)
A practical application of this could be calling a process that would spawn a VM to spin up. Here we will just print the name but you could execute a shell command that would spawn a widget.
1 2 3 4 |
; html-script: false ]subprocess.Popen(""" nova boot --flavor 1 --image <insert image ID here> --key_name \ ssh_key""" VMnameFromPython """, shell=True, stdin=None, executable="/bin/bash""") |
Class and Method Examples
So here are a couple of easy peasy examples that should help you get a kickstart, think of code reusability and as why you would add this extra complexity. Also you notice what happens when we try and print from the method, it returns ‘none’, in the next example we will change that to return which can be useful to break out of methods and also return parameters back from the method while pass would be indicate and empty block statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
; html-script: false ]#!/usr/bin/python class VMname: def createVM(self, name): #Remember Self just refers to the object you are passing firstHot or secondHost self.name=name #Initialize the argument we passed with the object def stateVM(self): print(self.name) #Create your first object firstHost = VMname() firstHost.createVM('email.foo.org') Hname1 = firstHost.stateVM() print('You named your VM ' + str(Hname1)) #Create your second object secondHost = VMname() secondHost.createVM('ldap.bar.org') Hname2 = secondHost.stateVM() print('You named your VM ' + str(Hname2)) #Notice what gets printed when we call the method stateVM, it prints 'None" #If we replace print(self.name) with return(self.name) #it will pass the attribute back outside of the class. #Next we call a method directly using the variable assigned to the object and class "firstHost" with a ".statVM() calling the method. #It will not pass back data from the class without us using return. #Notice it says none. print(firstHost.stateVM()) print(Hname2) |
The output looks like this:
1 2 3 4 5 6 7 8 9 |
; html-script: false ]email.foo.org You named your VM None ldap.bar.org You named your VM None email.foo.org None None |
Return Statement from a Function or Method in a Class
Let’s add the ‘return‘ statement and add a bit of formatting. Return allows us to use the method data from the class outside of the class. I also added a couple of different ways to print strings in there for reference:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
; html-script: false ]#!/usr/bin/python class VMname: def createVM(self, name): self.name=name def stateVM(self): print('Your VMname is %s' % self.name) print('Another Way to print the string from the method ' + self.name) return(self.name) firstHost = VMname() firstHost.createVM('email.foo.org') Hname1 = firstHost.stateVM() print('A third way to print your 1st VM ' + str(Hname1)) secondHost = VMname() secondHost.createVM('ldap.bar.org') Hname2 = secondHost.stateVM() print('A third way to print your 2nd VM ' + str(Hname2)) |
The output looks like this:
1 2 3 4 5 6 7 8 |
; html-script: false ]Your VMname is email.foo.org Another Way to print the string from the method email.foo.org A third way to print your 1st VM email.foo.org Your VMname is ldap.bar.org Another Way to print the string from the method ldap.bar.org A third way to print your 2nd VM ldap.bar.org |
Constructors the Magical Method __init__ Example
When a instance of a class is created the initializer is called with __init__, this can set default values and can save you from explicitly initializing a class with something like “firstHost = VMname()” in our previous example. C+ constructors are a similar concept. Clear as mud!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
; html-script: false ]#Example #1 Class class VMname: def createVM(self, name): self.name=name def stateVM(self): print('Printing from the 1st Class Example ' + self.name) print() #Adding Whitespace #Explicitly initializing the Class example1 = VMname() example1.createVM('classEx.foo.org') example1.stateVM() #Example #3 What the heck is this __init__? class VMname1: def __init__(self, name): self.name=name def stateVM1(self): print('Printing from the 2nd Class Example ' + self.name) print() #Adding Whitespace #__init__ initializes the Class example2 = VMname1('constructorEx.foo.org') example2.stateVM1() #Example #3 Predefined Data class VMname2: def __init__(self, name='predefinedvarsEx.foo.org'): self.name=name def stateVM2(self): print('Printing from the 3rd Class Example ' + self.name) print() #Adding Whitespace #__init__ initializes the Class and a predefined value for name example3 = VMname2() example3.stateVM2() |
Here is the exciting output and names of our hosts!
1 2 3 4 5 6 7 |
; html-script: false ]Printing from the 1st Class Example classEx.foo.org Printing from the 2nd Class Example constructorEx.foo.org Printing from the 3rd Class Example predefinedvarsEx.foo.org |
That does it for this one. Excuse mistakes and bad concepts, a lot of this can be open to interpretation or just flat wrong but the examples are what I need mostly so hopefully those will help those visiting Python or knocking off the rust. More Tutorials in the Programming section.
- More Python tutorials: Functions and Passing Lists and Dictionaries with Simple Examples
Thanks for stopping by.
Thank you so much! Such a simple and easy way of putting it. Well done. Thanks!
Thanks Ciprian!
Respect,
-Brent
Was looking for a basic python tutorial since I am full retard when it comes to OOP python. It’s amazing i found this…
Thanks man, took a while to find but helped alot
Thanks very much It help me a lot. I have been looking for an article like this until I found it today.