ezoic

Wednesday, November 9, 2016

How to pratically learn python from zero: chapter four: Classes

There is a concept called OOP in computer science.It is called object-oriented programming.

Object-oriented programming (OOP) is a programming language model organized around objects rather than "actions" and data rather than logic. Historically, a program has been viewed as a logical procedure that takes input data, processes it, and produces output data.

In Python, accordingly, there is a concept called 'classes', it makes the Python programming become OOP. It mainly groups some functions together and make a class. If you feel OOP is difficult to understand or something, you can interpret class to be a bunch of functions grouped together to fulfill a task etc.

Since class is a list of functions, first we need to learn to write a function in python. It has the following format:

def functionname( parameters ):
   "function_docstring"
   function_suite
   return [expression]
 
 
Here is a simple example:
 
def cal1(x,y):
     z=x+y
     return z
print cal1(5,6)
 
output:
 
11
 
Python naming convention:
 
1. Never use the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), or 'I' (uppercase letter eye) as single character 
variable names.
2. Package and Module Names:
Modules should have short, all-lowercase names.  Underscores can be used in the module name if it improves readability. 
 Python packages should also have short, all-lowercase names, although the use of underscores is discouraged.
3. Class names should normally use the CapWords convention.
     
 
Basic format of a class in python is like:
 
class ClassName:
    <statement-1>
    ......
   <statement-n>
 
And in a class, there is an instantiation operation which is for a specific initial state. Therefore a class may define a 
special method named __init__  like this: 
 
def __init__(self):
    self.data=[]

But for some of the classes, we can skip the initial steps, i.e. not include __init__ in our class. 
 
After the __init__, we can add more functions. 
 
Here is simple class called Dog:
 
class Dog:

    def __init__(self, name):
        self.name = name
        self.tricks = []    # creates a new empty list for each dog

    def add_trick(self, trick):
        self.tricks.append(trick)
 
And we can start a class instance like below:
 
d=Dog('Puppy')
And use the function in the class:
d.add_tricks('roll over')
 
And the original class will change the values:
d.tricks
['roll over']
 
  
 
    


 

No comments:

Post a Comment

looking for a man

 I am a mid aged woman. I live in southern california.  I was born in 1980. I do not have any kid. no compliacted dating.  I am looking for ...