Classes in Python
There are loads of content and age old story telling way of explain classes , I take it the nerdy way and explain on the technical part of it , in this post .
Defining a class
class ClassName:
{statement-1}
.
.
.
{statement-N}
The statements can be simple statements or it can be methods .Normally the contain methods.
Class Objects:
These supports ===> attribute references and instantiation
To understand , those two lets consider a simple class definition :
class YouNity:
"My first class"
bond = 007
def hi(self):
return 'hello world'
Attribute reference ==> YouNity.bond or YouNity.hi()
Instantiation ===> all = YouNity () , creates a new instance of the class and assigns this object to the local variable all .Hence , we can access varibales and methods of the class , as all.bond or all.hi()
__init__() ans self
This method is very much similar to the Java constructor , lets see how it can be used ?!
>>> class Who:
... def __init__(self, first, last):
... self.firstName = first
... self.lastName = last
...
>>> name = Who("hemanth", "hm")
>>> name.first,name.last
(hemanth,hm)
In the above example , the __init__ method is called when the class is instantiated , the first argument to the method is called "self" , the name self has absolutely no special meaning to Python , but can be understood as the current variables reference.
Inheritance
The child must follow the parent class , that is Derived followed by Base class in the declaration.
class DerivedClassName(BaseClassName):
{statement-1}
.
.
.
{statement-N}
If the Base is in some other package then ?
class DerivedClassName(modname.BaseClassName):
Multiple parents to a single child !!!
class DerivedClassName(Base1, Base2, Base3):
{statement-1}
.
.
.
{statement-N}
Recent blog posts
- watir-webdriver web inspector
- gem list to gemfile
- Packing ruby2.0 on debian.
- Made it into The Guinness Book!
- to_h in ruby 2.0
- Filter elements by pattern jQuery.
- Better HTML password fields for mobile ?
- Grayscale image when user offline
- nth-child CSS pseudo-class Christmas colors
- EventEmitter in nodejs