Thursday, October 6, 2016

[ Objected-Oriented Programming ] Classes

Three paradigms of programming

  • Imperative
    • statements , loops , functions as subroutines
  • functional
    • pure functions , high-order functions , recursion
  •  Objected-Oriented Programming
    • classes , objects 

Objects are created using classes 
Class is separate from the object itself
Method is object's function

>>>
class Cat :
  def_init_(self,color,legs):
    self.color = color
    self.legs = legs


felix = Cat("ginger",4)
rover = Cat ("brown",3)


This code define a class names Cat , which has two "attributes" color and legs.



__init__
  • The __init__ method , is called when an instance(object) of the class is created,using the class name as function.
  • All method must have self as their first parameter . although it isn't explicity passed,Python  adds the self argument to the list for you .you don't need to include it when you call the methods.
  • In an __init__method , self ,attribute can therefore be used to set the initial value of an instance's attributes.
  • The __init__ method is called the class constructor

Method
  • Classes can have other method define to add functionality to them
  • All methods must have self as their first parameter

>>>
class Dog:
  def __init__ (self,name,color):
    self.name = name
    self.color = color

  def bark(self):
    print("Woof!")

fido = Dog("Fido","brown")
print_(fino.name)
fido.bark()


Class Attribute
  • are shared by all instances of the class
>>>
class Dog: 
  legs = 4
  def __init__ (self,name,color):
    self.name = name
    self.color = color

fido = Dog("Fido","brown")
print_(fino.legs)
print_(Dogs.legs)

Attribute Error (undefined Attribute , Method)


No comments:

Post a Comment