Python basics: Object-oriented

Source: Internet
Author: User
Tags instance method

First, the definition

Object-oriented is a programmatic approach that is implemented based on the use of classes and objects

Class: A kind, a model.
Object: Refers to the specific thing, the model is made of things called objects.
Instance: the instance and object are the same.
Instantiation: Instantiation is the process of making things.
Property: Is the variable
Method: Is the function inside the class

Definition of the class:

class Person:  # class    def__init__(self):# constructor        self.name = ' Zhang '        #  #公有属性    def driver (self):#  Method        print(' old driver, drive very steady ') p=person ()# instantiation, P is an instance of an object
Print (p.name) #实例化对象可调用类的公共属性
P.driver () #实例化对象可调用类的公共方法

Second, the structure function:

__init__ (self) This is a constructor function. can write not write. When the class is instantiated, the constructor is executed first. Constructors can also take parameters. If the constructor takes a parameter, it is instantiated with a parameter

class Person:  # class    def__init__(self,age):#带参数的 constructor        ' Zhang ' # #公有属性   self.age= agep =person (#实例化),                  The value of age must be brought past print (p.age)# Printing

Third, self

The

Self represents this class of objects. Because the variables inside the function are local variables, the function cannot be used. After the
has been bound to the object with self, it can be self.xx casually

class Person:  # class    def__init__(self,age):# Constructors        with parameters ' Zhang ' # #公有属性   self.age= age def haha (                         Self):        print (self.nose)# You can use the variables in the constructor directly with Self.nose and print out 2        p =person (18)

Iv. Private properties and methods

The definition of a private property and method, preceded by two horizontal. Private properties and methods can only be called inside a class. The class body cannot be called again.

classPerson:#class    def __init__(self):#constructor FunctionSelf.name ='Zhang'Self.nose= 2##公有属性Self.__ear=2#private property, variable before add __    defDriver (self):#Method        Print('old driver, drive very steady.')    def __eat(self):#Private Methods        Print('eat ..... ') P=person ()#instantiation, P is an instance of an objectPrint(p.__ear)#ErrorP.__ear()#error, private method only valid within the class, out of class can not call

Five, attribute method

Methods that look like attributes. The difference from the normal method: Add @property before the method. Called when the property is called, without parentheses

classBaby ():#No Constructors    defMy (self): Self.name='AAA'    defCry (self):#instance Method        Print('whoa, whoa .') @property#Property Method    defHHH (self):return198b=Baby () b.cry ()Print(B.HHH)#the invocation of a property method is the same as calling a property, without parentheses after the method name

Six, class variables

Variables that can be referenced and manipulated directly through the class name. An instance can also reference an operation, but the instance does not actually change the value of a class variable

Class variables are defined directly within the class (not defined in the body of the function)

classBaby (): Country=' China' #class variables, common variables, each instance can be used    defMy (self): Self.name='AAA'    defCry (self):#instance Method        Print('whoa, whoa .')
Print (self.country) #函数调用类变量时, use SELF.XXXB=Baby () b.country='Zhongguo'#instance object modifies the value of a class variablePrint(B.coutry)#Print out ZhongguoPrint(Baby.country)#class directly calls the class scalar, which is still the original value of China, and does not change
baby.country= ' Japan ' #类变量可通过 class. Xxx=xx modification
Print (baby.country) #打印出japan

Vii. Types of methods

A class method can be called directly from an instance or directly with a class name. The definition of a class method needs to be preceded by a common method @classmethod

classBaby (): Country=' China'#class variables, public variables, all instantiated objects are available    #def __init__ (self): #构造函数不是必须写的    #print ( self)    #Self.name=name    defCry (self):#a method with self, called an instance method. You must instantiate before you can call        Print('Oh, whoa .')
Print (Self.xiaoming ()) #调用类方法时, you must use Self.xxx @property#with this sentence, the function is defined as a property method, which is used as a variable. Cannot join the parameter defHHH (self):return198@classmethoddefXiaoming (CLS):#The CLS represents this class, which is the class method Print(cls.country)Print('I am the class method') b=Baby () b.xiaoming ()#Instance object Call class methodBaby.xiaoming ()#class names call class methods directly

Viii. static methods

#静态方法就是一个普通的函数, just write in the class, you can not use class variables, class methods, and can not use instance methods, instance variables. The definition of a static method is preceded by a normal method plus @staticmethod
class byby ():    @staticmethod    def  Xiaohei ():        print('  This is a static method, which is the same as a function that does not unload the class )

Nine, the destruction function

The destructor is executed when the instance is destroyed and is generally used as the last good tail work. For example, in a database operation, you can put the shutdown action in the destructor, when the program is all executed, the destructor is automatically executed, the database connection is closed

Destructors are also non-mandatory

ImportPymysqlclassMyDb (object):def __del__(self):#destructors are not necessarily written        # Destructorsself.cur.close () #将数据库关闭操作放在析构函数. After the program finishes executing, the destructor self.conn.close () #Print('Over ....')    def __init__(self,host,user,password,db,port=3306,charset='UTF8'):        Try: Self.conn=pymysql.connect (host=host,user=user,password=password,port=port,charset=charset,db=db,autocommit=True)#autocommit can automatically commit a commit when executing a insert,update,delete statement        exceptException as E:Print('database connection failed%s'%e)Else: Self.cur=self.conn.cursor (cursor=pymysql.cursors.DictCursor)defEx_sql (self,sql):Try: Self.cur.execute (SQL)exceptException as E:Print('SQL statement has problem%s'%sql)Else: Self.res=Self.cur.fetchall ()returnSelf.resmy=mydb ('127.0.0.1','Root','123456','DB') My.ex_sql ('select * from Stu;')Print('last line ...'#程序自上向下执行, after the execution of this line of code, the program ends and the destructor is executed

#所以最终会看到打印结果中显示:
Last line ...
Over ...

Ten, if __name__ = = ' __main__ ':

Role:

1. Determine if the Python file was imported elsewhere or run the Python file directly

2, this sentence is generally used for testing purposes, the direct implementation of the sentence where the document, plus and no difference

3. However, if you import the file in another file, all the code under main will not be executed

Suppose the code in the file aa.py is as follows:

Print (__name__) # executes the file directly and prints out the __main__. But if you import the file in another file, this word back prints out the current file's filename if__name__'__main__':#    Running the current Python file directly, main writing here is not much use. Write and do not write the same # But if you import the current Python file in another python, the code under main will not be executed    print (' Test ... '). ‘)

The above code, if run directly in the Py file, will print out:

__main__

Test......

If you import aa.py in file b.py, execute the result:

The file name of the AA #直接打印出aa. py. The code under if__name__== ' __main__ ' is not executed at the same time

Python basics: Object-oriented

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.