As already discussed in Introduction to Python post, Python is a multi-paradigm language which could work as structured programming, object-oriented programming or functional programming.
Object Oriented Programming (OOP according to its acronym) is a programming paradigm in which concepts relevant to our problem real world are modeled through classes and objects, and in which our program is a series of interactions between these objects.
CLASSES AND OBJECTS
To understand this paradigm we must first understand what a class and what is an object. An object is an entity that brings together a state and functionality related. The object state is defined by variables called attributes, while functionality is modeled by functions that are called by the name of the object methods.
An example of object could be a car, which would have attributes such as brand, the number of doors or the type of fuel and methods such as start and stop. Or any other combination of attributes and methods as it was relevant to our program.
Class, moreover, is nothing but a generic template from which to instantiate objects;template that is what defines what attributes and methods will the objects of that class.
Returning to our example: In the real world there is a set of objects that we call cars and have a common set of attributes and a common behavior, this is what we call class.However, my car is not like my neighbor’s car, and although they belong to the same class of objects but are different objects.
In Python classes are defined by the keyword
class followed by the class name, a colon (:) and then indented, the body of the class. As in the case of functions, if the first line of the body is a string, this is the string class documentation or doc string
class car : "" " Abstraction of objects car. " "" def __init__ (self, petrol) gasoline self.gasoline = print " We " , gasoline, " l " def start (self): if self.gasoline> 0 : print " start " else : print " No start ... " def drive (self): if self.gasoline> 0: self.gasoline - = 1 print " remain " , self.gasoline, " l " else : print " It does not move ... "
The first thing that draws attention in the above example is the curious name that has the __init__ method. This name is a convention, not a whim. The __init__ method, with a double bar low at the beginning and end of the name, is executed just after creating a new object from the class, a process known as instantiation. The __init__ method is, as the name suggests, to perform any initialization process necessary.
As we see the first parameter __init__ and other methods of the class it is always
self .This is an idea inspired by Module-3 and used to refer to the current object. This mechanism is required to access the attributes and methods of the object differentiating, for example, a local variable
my_var an attribute of the object
Returning to the method
__init__ our class
Car will see how to use
self gasoline to assign the attribute of the object (
self.gasoline ) the value specified for the programmer parameter
gasoline . The parameter
gasoline is destroyed at the end of the function, while the attribute
petrol is conserved (and can be accessed) while the object is alive.
To create an object class name followed by any parameters necessary brackets write.These parameters are to be passed to the method
__init__ , which as we said is the method called to instantiate the class.
my_car = Car (3)
Then you will wonder how it is that when it comes to creating our first object we pass one parameter to
__init__ , number 3, when the function definition clearly indicates that requires two parameters (
gasoline ). This is because Python passes the first argument (the reference to the object being created) automatically.
Now that we have created our object, we can access its attributes and methods using the syntax
object.method () :
>>>print my_car.gasoline 3 >>>my_car.start .start () Start >>> my_car.drive () remain 2 liters >>> mi_car.drive () remain 1 liters >>> mi_car.drive () remain 0 liters >>> mi_car.drive () it does not move ... >>> mi_car.start () does not start ... >>> print my_car.gasoline 0
As a final note to remember that in Python, as repeatedly discussed above, all are objects.Chains, for example, have methods like
upper() , which returns the text in uppercase or
count(sub) , which returns the number of times the string was found
There are three concepts that are basic to any programming language object-oriented: encapsulation, inheritance and Polymorphism.
In an object-oriented when we make a class (subclass) inherits from another class (superclass) are making subclass contains all the attributes and methods that had the superclass language. However the act of inheriting a class is also often called “extend a class.”
Suppose we want to model musical instruments in a band, then we have a guitar class, a battery class, low class, etc. Each of these classes have a number of attributes and methods, but it happens that, for the sake of being musical instruments, these classes will share many of its attributes and methods; an example would play method.
It is easier to create a type of instrument being with common attributes and methods and tell the program to guitar, drums and bass are types of instruments, making inherit instrument.
To indicate that a class inherits from another the name of the class that is inherited in parentheses after the class name is placed:
class instrument : def __init__(self, amount): self.price = amount def play(self): print " We are playing music " def break (self): print " That you pay your " print " Son " , self.price, " $$$ " class Battery(Instrument): pass class Guitar(Instrument): pass
Guitar inherited from
Instrument , both have a touch method and breaking method, and passing a parameter initialized
price . But what would happen if we enter a new parameter
which_string when creating an object
Guitar ? Suffice to write a new method
__init__ for class
Guitar to be implemented instead of
However, it may happen in some cases we need to override a method in the parent class, but in this method we want to execute the method of the parent class because our new method no longer need to run a couple of extra new instructions. In that case we would use the syntax
SuperClase.metodo (self, args) ; for example, to call the method
guitar would use
Instrument .__ init __ (self, amount)
Notice that in this case you if you need to specify the self parameter.
In Python, unlike other languages
class crocodile (land, water): pass
In the event that any of the parent classes have methods with the same name and number of parameters they would overwrite classes implement the methods of classes over to his right in the definition. In the following example, as Earth is furthest to the left, would be the defining move of this kind would prevail, and therefore if we call the method move of a crocodile object that would print would be “The animal walk.”
class Land : def move(self): print " The animal Walks " class Water : def move(self): print " The animal swims " class crocodile(land, water) pass c = crocodile() c.move()
The word polymorphism, Latin morpho polys (various forms), refers to the ability of different classes of objects respond to the same message. This can be achieved through inheritance an object of a derived class is both an object of the parent class, so that wherever an object of the parent class can also use one of the child class is required.
Python, being dynamic typing does not impose restrictions on the types that can be passed to a function, for example, beyond the object behaves as expected: if you are going to call a method f of the object passed as parameter, for example, clearly the object will have to reckon with that method. For this reason, unlike statically typed languages
Sometimes also polymorphism the term is used to refer to method overloading, a term which is defined as the ability of language to determine which method to run several methods with the same name as the type or number of parameters passed to it. In Python there is no method overloading (the latter method would overwrite the implementation of the above), but you can get similar behavior functions using default values
Encapsulation refers to prevent access to certain methods and attributes of the objects thus establishing what can be used from outside the class.
This is achieved in other programming languages
In Python there are no access modifiers, and what is usually done is that access to a variable or function is determined by its name: if the name begins with two underscores (and not also end with two underscores) it is of a variable or private function, otherwise it is public. Methods whose name begins and ends with two underscores are special methods that Python automatically calls under certain circumstances, as discussed at the end of the article.
The following example only public method for the string is printed, while trying to call the Python method __private throw an exception complaining that does not exist (evidently exists, but we can not see because it is private).
class Example : def public(self): print " Public " def __private(self): print " Private " eg = Example() eg.public() eg.__private()
This mechanism is based on the names that begin with a double underscore are renamed to include the name of the class. This means that the method or attribute is not really private, and can be accessed through a small trap:
Sometimes this can happen that we want to allow access to any attributes of our object, but this occurs in a controlled manner. To this we can write methods whose sole purpose is the methods that usually, by convention, have names like getVariable and setVariable;hence it is also known by the name of getters and setters.
class date(): def __init__(self): self.__ day = 1 def getDia (self): return self.__day def setDay (self, day): if day > 0 and day <31: self.__day = day else : print "Error" my_date = date() mi_date.setDay(33)
This could be simplified by properties, abstracting the user of the fact that they are using methods behind the scenes to obtain and modify the attribute values:
class Date(object): def __init__(self): self.__ day = 1 def getDay(self): return self.__day def setDay(self, day): if day> 0 and day <31: self.__ day = day else : print "Error" day = property(getDay, setDay) my_date = Date() mi_date.day = 33
TYPES OF “NEW-STYLES”
In the above example you will be struck by the fact that the class object derives from Date. The reason for this is that in order to use the class properties must be “new-style” classes enriched introduced in Python 2.2 to be the standard in Python 3.0 but still live with the “classic” for reasons of backward classes. In addition to the properties of new-style classes added other features such as descriptors or static methods.
For a new-style class is necessary, for now, to extend a kind of new-style. In case it is not necessary to inherit the behavior or condition of any kind, as in our previous example, you can inherit from object, which is an empty object that serves as the basis for all kinds of new style.
The main difference between the old school and new style is that when creating a new class previously not a new type is actually defined, but all the objects created from classes, these classes were to be, they were kind of
We saw earlier in this article using the __init__ method. Other methods with special meanings, whose names always begin and end with two underscores. Some especially useful are listed.
__init __ (self, args)
method called after creating the object to perform initialization tasks.
__new __ (cls, args)
Method of exclusive new-style classes that runs before __init__ and is responsible for building and return the object itself. It is equivalent to the builders of C ++ or Java. This is a static method, ie, which exists independently of the instances of the class is a class method and not of purpose, and therefore the first parameter is not
self , but the class itself:
__del __ (self)
Method called when the object to be deleted. Also called destroyer, it is used for cleaning.
__str __ (self)
Method called to create a text string that represents our object. It is used when using print to show our object or when we use the function
str (obj) to create a string from our object.
__cmp __ (self, other)
Method called when the comparison operators are used to check if our object is less than, greater than or equal to the object passed as a parameter. Must return a negative number if our object is less, zero if they are equal, and a positive number if our object is greater. If this method is not defined and you try to compare the object by operators <, <=,> or> = an exception is thrown. If operators == and! = Operators to check if two objects are equal, it is checked whether they are the same object (if they have the same id).
__len __ (self)
Method called to check the length of the object. It is used, for example, when calling the function
len (obj) on our object. As expected, the method should return the number the length of the object.
There are many more special methods, which allows among other things using the slicing mechanism on our object, use arithmetic operators or using dictionary syntax, but an exhaustive study of all methods is beyond the scope of the article.
if you want to know further about object orientation please check official python tutorials or you can also follow the Object Oriented Programming course at MIT where Video lectures are also available
Please feel free to comment below the any burning question you have. Will try best to help You Out :)