Geeks With Blogs
Josh Reuben


Back in the day, I did a fair bit of work with BioPython – I thought it was time to revisit this glue language !

Classes

Python allows for the definition of classes. The builtin __init__ function serves as the ctor. Remember to pass self as 1st param to all class functions

class MyClass():

def __init__(self):

self.y = 5

def doSomething(self):

pass

x = MyClass()

x.doSomething()


Static methods

use @classmethod to specify that a function is static – dont have to instantiate to call it.

class MyClass():

@classmethod

def doSomething(self):

pass

MyClass.doSomething()

Inheritance

Python supports inheritance. Import the abstract base class packages. For base classes, derive from object.

__metaclass__ specifies that a class is abstract, and @abstractmethod specifies that a function should be overridden. super allows calling a base class method. __subclasses__() lists all derived classes.

from abc import ABCMeta, abstractmethod

class MyBase(object):

__metaclass__ = ABCMeta

@abstractmethod

def doSomthing(self):

pass

class MyDerived(MyBase):

def __init__(self):

super(MyDerived, self).__init__() #call base ctor

print MyBase.__subclasses__()

Decorators

A decorator is a callable that takes a function as an argument and returns a replacement function. Use *args, **kwargs to pass param arrays and dynamic named arguments

def myDecorator(func):

def myDecoratorInternal(*args, **kwargs):

return func(*args, **kwargs) + 2

return myDecoratorInternal

@myDecorator

def myFunc(x=1):

return x

print myFunc() # prints 3

Singletons

using __new__ its pretty easy to define a singleton:

class MySingleton(object):

_instance = None

def __new__(self):

if not self._instance:

self._instance = super (MySingleton, self).__new__(self)

return self._instance

Can also use a Decorator to define a singleton:

def singleton(MyClass):

instances={} #dictionary of type instances --> can only be 1 of each

def getInstance(*args, **kwargs):

if MyClass not in instances:

instances[MyClass] = MyClass(*args, **kwargs)

return instances[MyClass]

return getInstance

@singleton

class AClass(object):

pass

x = AClass()


Or define a Singleton using a metaclass, using __call__:

class MySingleton(type):

_instances={} #dictionary of type instances --> can only be 1 of each

def __call__(cls, *args, **kwargs):

if cls not in cls._instances:

cls._instances[cls] = super(MySingleton, cls).__call__(*args, **kwargs)

return cls._instances[cls]

class MyClass(object):

__metaclass__ = MySingleton


Mixins and the Type syntax

Its also possible to define short classes using the type function, specifying external functions


def myMixIn(self):

pass

MyDerived = type("MyDerived", (MyBase,), {"x":5,"func": myMixIn})


Conclusion

Python is pretty easy – I'm exploring Cython, iPython, PyQt, SciPy, NumPy and SciKit-Learn next !

Posted on Sunday, March 1, 2015 6:30 PM | Back to top


Comments on this post: Python OOP

# re: Python OOP
Requesting Gravatar...
It is indeed, easy to follow through. This process is very useful. - Dr. Thomas G. Devlin MD, PhD
Left by James Michael on Dec 20, 2016 9:20 AM

Your comment:
 (will show your gravatar)


Copyright © JoshReuben | Powered by: GeeksWithBlogs.net