Object-Oriented Programming (base)

Object-Oriented Programming

The core object-oriented programming word is the object, the object is a combination of features and skills.

Object-oriented programming is based on the idea of ​​programming, is like creating a world, you are the God of this world, God is thinking way in style.

Advantages: Scalable strong

Disadvantages: complexity than process-oriented programming

Classes and Objects

Object is a combination of features and skills, the object class is a series of similar features skill combination.

The real world, there is a first concrete objects that existed only with the development of the concept of classification, Python program also has the concept of class, but Python program must first define the class and then call the class to create objects.

The real world is defined classes and objects

Custom object

  • Student categories:

    Similar characteristics:

    学校 = '北京大学'

    Similar skills:

    选课

Objects and classes defined in the program

The definition of class

# 注意类中定义变量使用驼峰体


class BeijingStudent():
    school = 'peking'

    def choose_course(self):
        print('is choosing course')

Defining a function, a function of detecting only the syntax, the code is not performed. But the definition of class, the class body will immediately execute the code in the class definition phase and will produce a class name space, which means that the class itself is actually a container / name space is used to store the name, this is one class of applications.

print(BeijingStudent.__dict__)
{'__module__': '__main__', 'school': 'peking', 'choose_course': <function BeijingStudent.choose_course at 0x000002A4E1AB5D08>, '__dict__': <attribute '__dict__' of 'BeijingStudent' objects>, '__weakref__': <attribute '__weakref__' of 'BeijingStudent' objects>, '__doc__': None}
print(BeijingStudent.__dict__['school'])
peking
print(BeijingStudent.__dict__['choose_course'])
<function BeijingStudent.choose_course at 0x000002A4E1AB5D08>
try:
    BeijingStudent.__dict__['choose_course']()

except Exception as e:
    print('error:', e)
error: choose_course() missing 1 required positional argument: 'self'
print(BeijingStudent.school)
peking
BeijingStudent.choose_course(111)
is choosing course
print(BeijingStudent.choose_course)
<function BeijingStudent.choose_course at 0x000002A4E1AB5E18>
BeijingStudent.__dict__['choose_course']
<function __main__.BeijingStudent.choose_course(self)>
BeijingStudent.country = 'China'
BeijingStudent.__dict__['country']
'China'
BeijingStudent.country = 'CHINA'
BeijingStudent.__dict__['country']
'CHINA'
del BeijingStudent.school
print(BeijingStudent.__dict__)
{'__module__': '__main__', 'choose_course': <function BeijingStudent.choose_course at 0x000002A4E1AB5E18>, '__dict__': <attribute '__dict__' of 'BeijingStudent' objects>, '__weakref__': <attribute '__weakref__' of 'BeijingStudent' objects>, '__doc__': None, 'country': 'CHINA'}

Custom object

Can call the class generates an object, procedure calls class, also known as the object is instantiated, the instance of the class known as the result of class / instance.

stu1 = BeijingStudent()  # 调用类会得到一个返回值,该返回值就是类的一个具体存在的对象/实例
print(stu1.country)
CHINA
stu2 = BeijingStudent()  # 调用类会得到一个返回值,该返回值就是类的一个具体存在的对象/实例
print(stu2.country)
CHINA
stu3 = BeijingStudent()  # 调用类会得到一个返回值,该返回值就是类的一个具体存在的对象/实例
stu3.choose_course()
is choosing course

Unique features custom objects

Function is a function defined in the class attribute class, a class can use, but use is a normal function of it, it implies the need for full compliance with the rules of function parameters, which pass several values ​​to pass a few.

Introduced

class BeijingStudent:
    school = 'peking'

    def choose_course(self):
        print('is choosing course')


stu1 = BeijingStudent()
stu2 = BeijingStudent()
stu3 = BeijingStudent()

For the above-mentioned class of students if the class attribute changed, the properties of other objects will change.

print(stu1.school)
BeijingStudent.school = 'PEKING'
peking
print(stu1.school)
PEKING

Unique features custom objects

print(stu1.__dict__)
{}
print(stu2.__dict__)
{}

Nature object similar to a class, but also a name space, but the name of the object space to store the object unique name, and class objects are stored in a common name. Therefore, we can directly target custom name alone.

stu1.name = 'tom'
stu1.age = 18
stu1.gender = 'male'

print(stu1.name, stu1.age, stu1.gender)
tom 18 male
try:
    print(stu2.name, stu2.age, stu2.gender)
except Exception as e:
    print(e)
'BeijingStudent' object has no attribute 'name'
stu2.name = 'jerry'
stu2.age = 18
stu2.gender = 'female'

print(stu2.name, stu2.age, stu2.gender)
jerry 18 female

Custom attribute class definition phase

def init(obj, x, y, z):
    obj.name = x
    obj.age = y
    obj.gender = z


init(stu1, 'tom1', 19, 'male1')
print(stu1.name, stu1.age, stu1.gender)
tom1 19 male1
init(stu2, 'jerry1', 29, 'female1')
print(stu2.name, stu2.age, stu2.gender)
jerry1 29 female1

Although using the above method allows us to tailor the properties simpler, but still too much trouble, if the timing properties can be triggered automatically when an object is instantiated, it is more convenient, so the class can use the __init__method.

class BeijingStudent:
    school = 'peking'

    def __init__(self, name, age, gender):
        '''调用类时自动触发'''
        self.name = name
        self.age = age
        self.gender = gender
        print('*'*20)

    def choose_course(self):
        print('is choosing course')


try:
    stu1 = BeijingStudent()
except Exception as e:
    print(e)
__init__() missing 3 required positional arguments: 'name', 'age', and 'gender'
stu1 = BeijingStudent('tom', 18, 'male')
********************
  • Can be found through the above phenomenon occurs when the calling class two things:
    • Create an empty object
    • Automatically trigger class __init__executive function, and the parameters within the stu1 call with the incoming class brackets
print(stu1.__dict__)
{'name': 'tom', 'age': 18, 'gender': 'male'}

Find a property of an object sequence

Find properties

  • Start with the object to find its own name space, then do not go to class to find, if the class nor the error
class BeijingStudent:
    school = 'peking'
    count = 0
    aa = 10

    def __init__(self, x, y, z):  # 会在调用类时自动触发
        self.name = x
        self.age = y
        self.gender = z
        BeijingStudent.count += 1

        self.aa = 1

    def choose_course(self):
        print('is choosing course')
print(BeijingStudent.count)
0
stu1 = BeijingStudent('tom', 18, 'male')
print(stu1.count)
1
stu2 = BeijingStudent('jerry', 19, 'male')
print(stu2.count)
2
stu3 = BeijingStudent('shane', 25, 'male')
print(stu3.count)
3
print(BeijingStudent.count)
3
  • Since the above modification of the properties of a class, the class attribute count 3 has been modified, the count of other examples are 3
print(stu1.count)
print(stu2.count)
print(stu3.count)
3
3
3
  • Since aa is private property, so they will use private stu aa, aa not use class
print(stu1.__dict__)
print(stu2.__dict__)
print(stu3.__dict__)
{'name': 'tom', 'age': 18, 'gender': 'male', 'aa': 1}
{'name': 'jerry', 'age': 19, 'gender': 'male', 'aa': 1}
{'name': 'shane', 'age': 25, 'gender': 'male', 'aa': 1}

Classes and Objects of binding method

Classes and Objects of binding method

class BeijingStudent:
    school = 'peking'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def choose_course(self):
        print(f'{self.name} is choosing course')

    def func(self):
        print('from func')
  • Class data attributes and function attributes are defined in a namespace for all shared objects with

  • Only data attributes defined object name space, and is unique to the object data attributes

Bound object class

stu1 = BeijingStudent('tom', 18, 'male')
stu2 = BeijingStudent('jerry', 19, 'male')
stu3 = BeijingStudent('shane', 25, 'male')


print(stu1.name)
print(stu1.school)
tom
peking
  • Function is a function defined in the class attribute class, a class can use, but use is a normal function of it, it implies the need for full compliance with the rules of function parameters, which pass several values ​​to pass several values.
print(BeijingStudent.choose_course)
<function BeijingStudent.choose_course at 0x000002A4E1C01268>
try:
    BeijingStudent.choose_course(123)
except Exception as e:
    print(e)
'int' object has no attribute 'name'

Bound method object

  • Class-defined functions are shared to all objects, the object may be used, and is bound to the subject with
  • Binding effect: Binding to whom, by whom they should call, who will call who will automatically passed as the first argument
print(id(stu1.choose_course))
print(id(stu2.choose_course))
print(id(stu3.choose_course))
print(id(BeijingStudent.choose_course))
2907183244104
2907183244104
2907183244104
2907185353320
print(id(stu1.school))
print(id(stu2.school))
print(id(stu3.school))
2907185318128
2907185318128
2907185318128
print(id(stu1.name), id(stu2.name), id(stu3.name))
2907185317792 2907185319192 2907185317568
stu1.choose_course()
stu2.choose_course()
stu3.choose_course()
tom is choosing course
jerry is choosing course
shane is choosing course
  • Added: class defined functions, classes can really use, but in fact a function of the class definition in many cases are used to bind to the target, so the functions defined in the class should own a parameter self
stu1.func()
from func
BeijingStudent.func(1)
from func

Classes and data types

Classes and data types

  • Python3 unified concept of class and type is the type of class
class Foo:
    pass


obj = Foo()
print(type(obj))
<class '__main__.Foo'>
lis = [1, 2, 3]
lis2 = [4, 5, 6]
print(type(lis))
<class 'list'>
  • lis and lis2 are instantiated objects, methods and lis the append independent lis2
lis.append(7)
print(lis)
[1, 2, 3, 7]
print(lis2)
[4, 5, 6]

list.append () method principle

class BeijingStudent:
    school = 'peking'

    def __init__(self, name, age, gender):
        self.name = name
        self.age = age
        self.gender = gender

    def choose_course(self, name):
        print(f'{name} is choosing course')


stu1 = BeijingStudent('tom', 18, 'male')
stu1.choose_course(1)  # BeijingStudent.choose_course(stu1,1)
1 is choosing course
BeijingStudent.choose_course(stu1, 1)
1 is choosing course
lis = [1, 2, 3]
print(type(lis))
<class 'list'>
lis.append(4)
print(lis)
[1, 2, 3, 4]
list.append(lis, 5)
print(lis)
[1, 2, 3, 4, 5]

Highly integrated object

No object

  • To connect to the database, for example, if the object does not face the thought, we just want to use a method, you have to do it
import pymysql  # 连接mysql的三方库,可以pip3 install pymysql安装


def exc1(host, port, db, charset, sql):
    conn = pymysql.connect(host, port, db, charset)
    conn.execute(sql)
    return xxx


def exc2(proc_name):
    conn = pymysql.connect(host, port, db, charsett)
    conn.call_proc(sql)
    return xxx


exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t1')
exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t2')
exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t3')
exc1('1.1.1.1', 3306, 'db1', 'utf-8', 'select * from t4')
  • As the host, port, db, charset may be fixed, sql has been changing, so we implement different sql statement by the above method, very troublesome, so we can use the default parameter
def exc1(sql, host='1.1.1.1', port=3306, db='db1', charset='utf-8'):
    conn = pymysql.connect(host, port, db, charset)
    conn.execute(sql)
    return xxx


exc1('select * from t1')
exc1('select * from t2')
exc1('select * from t3')
exc1('select * from t4')
  • Although the default parameters are used to simplify the operation, but for different objects referenced parameter is not static, or we need to be modified exc2 method, which is very troublesome, it is possible to consider the use of object-oriented

There are objects

  • With object-after, for the above example, we can do this
import pymysql


class Foo:
    def __init__(self, host, port, db, charset):
        self.host = host
        self.port = port
        self.db = db
        self.chartset = chartset

    def exc1(self, sql):
        conn = pymysql.connect(self.host, self.port, self.db, self.charset)
        conn.execute(sql)
        return xxx

    def exc2(self, proc_name):
        conn = pymysql.connect(self.host, self.port, self.db, self.charsett)
        conn.call_proc(sql)
        return xxx


obj1 = Foo('1.1.1.1', 3306, 'db1', 'utf-8')
obj1.exc1('select * from t1')
obj1.exc1('select * from t2')
obj1.exc1('select * from t3')
obj1.exc1('select * from t4')

obj2 = Foo('1.1.1.2', 3306, 'db1', 'utf-8')
obj2.exc1('select * from t4')
  • For the above phenomenon occurs, we can conclude that the object is actually a highly integrated product, the integration of data and special methods of operation of the data (binding method)

Guess you like

Origin www.cnblogs.com/WilliamKong94/p/11123172.html