Friday, July 7, 2017

Summer of code 2017: Python, Day 20 Classes


As explained in my Summer of code 2017: Python post I decided to pick up Python

This is officially day 20. today I will take a look at classes

All types in Python have a class
Class instances are created by calling the class as if it were a function


Here is the simplest form of a class

class Test:
    """description of class"""
 
   
 
    def val(self, val):
        return val

If we now instantiate the class and pass in the string "denis' to the val method, the string is returned


>>> f = Test()
>>> print(f.val("denis"))
denis
>>> 

In Python self is similar to this in Java or c#

Implementation details are denoted by a leading underscore, in Python there are no public, protected or private access modifiers like in Java or c#



Here is an example of the class where we added __init__ and we are also returning _val instead of val

class Test:
    """description of class"""
 
    def __init__(self, val):
        self._val = val
 
    def val(self):
        return self._val

Here is what the output looks like now

>>> f = Test("denis")
>>> print(f.val())
denis
>>> f = Test("yo")
>>> print(f.val())
yo
>>> 

As you can see it is all pretty simple stuff at this point

To do inheritance, you add the base class name in parentheses after the class name. So if a class SomeTest inherits from Test, you would specify it like this:  class SomeTest(Test)

Here is what the code looks like for both classes

class Test:
    """description of class"""
 
    def __init__(self, val):
        self._val = val
 
    def val(self):
        return self._val
 
 
class SomeTest(Test):
    """description of class"""
 
 
    def someVal(self):
        return self._val


Now we can call both the val and someVal methods from the SomeTest class because the val method exists in the test class from which the SomeTest class inherits

Here is the output

>>> f = Test("yo")
>>> print(f.val())
yo
>>> g = SomeTest("Den")
>>> print(g.val())
Den
>>> print(g.someVal())
Den
>>> 


I am sure I will be revisiting and adding to my notes when I start messing around with classes more

That is it.. a short post for a short Holiday week in the US


No comments: