Python: Object-oriented and class

Source: Internet
Author: User


process-oriented and object-oriented programming ideas:
Object-oriented--object oriented programming, short for OOP, is a programming idea. Before we talk about object-oriented, let's talk about what is the programming paradigm, the programming paradigm, and the way you go about programming, to implement a function. For example, you have to cook,
can use induction cooker, also can use gas stove. The different programming paradigms essentially represent the different problem-solving ideas taken for various types of tasks, and the two most important programming paradigms are process-oriented programming and object-oriented programming.
Referring to object-oriented, we have to mention another kind of programming idea, process-oriented, what is the process-oriented idea is to put a project, a thing in a certain order, from beginning to end, do what first, what to do, all the way down to the finish. This
Kind of thinking better understanding, in fact, this is also a way of doing things, our previous programming ideas are also using this idea. This programming idea, as long as there is a step in front of the change, then the back will be changed, behind the maintenance of more trouble, such a programming idea, I
We can use it when we write simple small programs and scripts that execute only once. Object oriented, object-oriented thinking is to divide a project, a thing into smaller projects, or into a smaller part, each part responsible for what aspects of the function, and finally by
These parts are combined and become a whole. This kind of thought is more suitable for many people's Division of labor, like a large organ, divided into various departments, each department is responsible for a certain function, each department can give full play to their own characteristics, as long as a certain premise on the line.
For example: For example, just said a large organ, to do a certain project, from the process-oriented thinking, it should be this analysis, first how, then how, finally how. How the first should be done, how the second should be done, and so on. Wait until each step is
Completed, the project will be completed. And the object-oriented thought should be like this, the project is composed of several parts, we will do a division, set up a department to do a part of the function of another department to do another part. Different departments can not understand other
department, as long as the completion of their own part of the matter is OK.

Object-oriented features: Classes, objects, instantiation
classes: class
class, compared to the real world, is a kind, a model.
A class is an abstraction, a blueprint, a prototype for a class of objects that have the same properties.
The properties of these objects (variables (data)) and common methods are defined in the class.
objects: Object
Object, also known as an instance, refers to the concrete thing created by the model.
An object is an instantiated instance of a class, a class must be instantiated before it can be called in a program, a class can instantiate multiple objects, and each object can have different properties, as human beings refer to everyone, each person refers to a specific object,
There are similarities and differences before people.
Instantiation:
Initializes a class, creating an object. The process of turning a class into a concrete object is called instantiation.
Properties:
For example, car color, brand, displacement;
Features:
For example, the car has the function of navigation, listening to songs, running, etc.
Class Buycar (object):
#新式类
Pass
Class BuyCar2:
#经典类
Pass
#python3里面经典类和新式类没有任何的区别, the general use of new classes when writing

#创建类
Class Buycar (object): #object是基类
def sale (self): #类里面函数默认加上self, do not write error
#self代表实例化之后的这个对象, designed to save memory
Print (' Sell car ')
def insurance (self):
Print (' Buy insurance ')
def check (self):
Print (' Car inspection ')
def card (self):
Print (' Select card ')
def pay (self):
Print (' Payment ')
def done (self):
Print (' Done ')
#类不能是直接用; can use an instance or an object

#实例化:
Me=buycar () #这个过程就是实例化对象, Me is an instance, also called an object
#如果是函数名加括号, which is called the function
#如果是类名加括号, which is the instantiation of the object
Me.sale ()
Me.check ()
Me.card () #实例化后, an object can call a method inside a class (that is, a function)

# Construction method, destructor method:
Class Car (object):
Wheel=4 #此处的wheel叫类变量, all instances can be used, and direct self.wheel can be used
def __init__ (Self,colors,pls,pzs): #__init__是构造方法
#构造方法在实例化这个类的时候就会执行, other methods must be called to execute
#如果想在类初始化的时候给它传一些参数, write the parameters in the construction method.
Self.color=colors
#给实例化的对象添加属性; here the color PL PZ is called an instance variable, distinguished from the class variable
Self.pl=pls
Self.pz=pzs
def __del__ (self):
#析构方法: The function is 1. When the object is destroyed (the Del instantiation object) executes
#2. Executes after the program runs, invokes the destructor at the end of the class's lifecycle, and then frees the memory
Print (' over ... ')
def driver (self):
Print (' The color of the car is: ', Self.color)
Self.run ()
#self在类里面代表实例化的对象, direct point. You can point it out. Defined properties and methods
Print (' Driver ')
def run (self):
Print (' Run ')
Your_car=car (' Red ', ' 5.0 ', ' Hummer ') #构造方法里的传参在实例化时直接填参数就可

Example:
Import Pymysql
Class Mydberror (Exception):
def __str__ (self):
Return ' Database connection error '
Class MyDb (object):
def __init__ (self,host,user,passwd,db,port=3306,charset= ' UTF8 '):
Try
Self.conn=pymysql.connect (
HOST=HOST,USER=USER,PASSWD=PASSWD,
Db=db,port=port,charset=charset
)
Except Exception as E:
Raise Mydberror
#主动抛出异常, if there is a raise, the program will not go down in the exception
Else
Self.cur=self.conn.cursor (Cursor=pymysql.cursors.dictcursor)

def select (self,sql):
Try
Self.cur.execute (SQL)
Except Exception as E:
Return E
Return Self.cur.fetchall ()
def other (Self,sql):
Try
Self.cur.execute (SQL)
Except Exception as E:
Return E
Self.conn.commit ()
Return Self.cur.rowcount
#如果sql执行成功, returns the number of rows affected
def __del__ (self):
Self.cur.close ()
Self.conn.close () #这个类不用的时候, close the database by executing the destructor

#私有变量和私有方法:
Import xlrd
Class Readcase (object):
__name= ' hahaha '
#类变量加俩下划线是私有变量, only in class, out of class.
#比如出了这个类, it's wrong to instantiate R,r.__name, and it's not coming out.
def __set (self):
self.money=259999
#函数名前加俩下划线是私有方法
#只能在类里面调用, out of class access is not
def __init__ (self,f_name):
Self.fname=f_name
def read_case (self):
Book=xlrd.open_workbook (Self.fname)
Pass
R=readcase (' A.xls ')


Package:
The implementation details of some functions are not exposed, the assignment of data in the class, the internal invocation is transparent to the external user, which makes the class become a capsule or container, in which the bread implies the data and methods of the class.

For example, create a person, you put his body inside of what heart spleen lungs and kidneys are sealed up, other people can not see, you directly find this person.

Inheritance:
A class can derive a subclass, and the properties, methods defined in the parent class automatically inherit the quilt class. For example, you inherit your father's surname.
Multi-Inheritance in Python3 is the breadth first, and the multi-inheritance of classical class in Python2 is the depth first, and the multi-inheritance of the new class is in the breadth first.
Inheritance is for the reuse of code
EG1:
class Person (object):
def __init__ (self,,name,sex):
Self.name=name
Self.sex=sex
Def cry (self):
Print (' cry ')
Class Man: #括号里填入Person is the property and method that inherits the person
def work (self):
Print (' Working ... ')
Hn=man (' HN ', ' NV ') #实例化Man, because the person is inherited, so you have to pass the argument when instantiating
Hn.name
Hn.cry ()
#实例化的Man, you can call methods and properties of the person
EG2:
Class Children (Person,man): #可以继承多个类
Pass
Hh=children (' hh ', ' nan ')
Hh.work ()
Hh.cry ()
#Multiple inheritance,There are methods and properties for the person man, children have
#多继承, if some of the inherited classes have name-like functions, the successor inherits by the first class in parentheses, which is called breadth-first in Python3.
#在python2里, if it is a classic class, it is depth first; new class words or breadth first


Polymorphic (Python does not directly support):
Sending the same message to different classes of objects will have different behavior. For example, if your boss lets all employees start working at nine o'clock, he says, "get started" at nine o'clock, instead of saying "start a sales job" to the salesperson:
Say to the technician: "Start technical work", because "employee" is an abstract thing, as long as the employee can start to work, he knows this is OK. As for each employee, of course, they do their job and do their jobs.
Polymorphism is a manifestation of abstraction that abstracts out the common denominator of a series of specific things and then, through this abstraction, dialogues with different specific things.
One method, multiple implementations.
EG1:
Class My (object):
def say (self,msg):
Print (msg)
def say (Self,age,sex):
Print (Age,sex)
def say (Self,addr,phone,money):
Print (Addr,phone,money)
#java里, polymorphism is implemented by different parameters, calling functions
#在python, the function name cannot be repeated, but can be indirectly implemented polymorphism, see below EG2
EG2
Class Cat (object):
def speak (self):
Print (' Meow meow ')
Class Dog (object):
def speak (self):
Print (' Wang Woo ')
C=cat ()
D=dog ()
OBJ=[C,D]
For i in obj:
I.speak () #通过这种方法间接实现多态 but not commonly used

overriding the constructor method of the parent class, the __str__ method
When overriding the constructor method of the parent class, you must first call the parent class's constructor, as shown below:
Class OpDb (object):
def __init__ (self,ip,passwd,port,db):
Self.ip=ip
self.passwd=passwd
Self.port=port
Self.db=db
Import Redis
Class Myredis (OPDB):
def set (SELF,K,V):
R=redis. Redis (HOST=SELF.IP,PORT=SELF.PORT,PASSWD=SELF.PASSWD,)
R.set (K,V)
Class MYSQL (OPDB):
def __init__ (self,ip,passwd,port,db,user,charset= ' UTF8 '):
# MySQL inherits the parent class opdb, but both of them have the __init__ method, when instantiating MySQL, call the MySQL own __init__ method
opdb.__init__ (SELF,IP,PASSWD,PORT,DB)
#想用到父类OpDb的__init__这个方法的话, you have to call this method of the parent class first.
#如果此处不调用OpDb的__init__方法, it is necessary to write Self.ip=ip self.passwd=passwd and so on, more trouble and low
#super (opdb,self). __init__ (IP,PASSWD,PORT,DB)
#super这个句子和上面调用父类OpDb的__init__方法的效果是一模一样的, Super, this is a little bit more advanced.
Self.user=user
Self.charset=charset
def __str__ (self):
Return "This is the class that executes the SQL"
Hn_mysql=mysql (' 192.168.1.1 ', ' 123456 ', 3306, ' test ', ' root ')
Print (Hn_mysql) #打印的结果不是Hn_Mysql的内存地址, but "this is the class that executes the SQL", __str__ method is this use

static methods, class methods:
Class Stu (object):
Country = ' China ' # class variable
def __init__ (self, name):
Self.name = Name
@staticmethod
Def say ():
# static method, add the function of the Staticmethod adorner, do not write self in parentheses, and the class itself has nothing to do with, it is equivalent to define a method in the class
Print (' xxx ')
@classmethod
def hello (CLS):
# This is called the class method, and the static method is different, it can use the class variable, must be passed a CLS, the representative of this class
Print (Cls.country)
def hi (self):
# This is an example method
Print (Self.name)
t = Stu (' name ')
Stu.hello ()
Stu.say ()
T.hi ()
T.say ()
T.hello ()

Python: Object-oriented and class

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.