python learning object-oriented foundation 27--

The concept of an object

 

"Object-oriented" is the core of the "object" of the word, but the essence of the object is "integration", what does that mean?

 

All programs are from the "data" and "functional" component, and thus the nature of programming is to define a series of data, and then define a series of functions to operate on the data. Before learning "object" in the program and data are separated, as follows

# 数据:name、age、sex
name='lili'
age=18 sex='female' # 功能:tell_info def tell_info(name,age,sex): print('<%s:%s:%s>' %(name,age,sex)) # 此时若想执行查看个人信息的功能,需要同时拿来两样东西,一类是功能tell_info,另外一类则是多个数据name、age、sex,然后才能执行,非常麻烦 tell_info(name,age,sex)

After learning of the "object", we have a container that can bloom and data capabilities, so we can say: The object is to integrate the data and functionality of the product together, or "object" is a bloom and function data container / box / boxes.

If the "data" compared to "mascara", "shadow", "Lip Gloss" and other raw materials needed to make-up; the "function" as a metaphor for the tool eyeliner, eyebrow pencil makeup and other needs, then the "object" is a Palette, make-up box can be "material" and "tools" are installed together

 

If we take the "make-up" as a metaphor for the business logic to be executed at this time can only bring one thing, and that is make-up box, because the makeup box incorporates all functions required raw materials and make-up, which were compared to you bring raw materials and functions to perform, to be more convenient.

 

After learning the basic concepts of object, object-oriented programming to understand the way a lot of relatively simple, object-oriented programming is to create a number of objects, the integration of the original spread of relevant data and functions into one object in , do not only easy to use, the solution can also increase the degree of coupling procedures, thereby enhancing the scalability of the program (needs to be emphasized that the property contains many aspects of software quality, object-oriented extensions to solve the problem merely)

 

Second-class object

That category class / category, is the cornerstone of an object-oriented analysis and design, if a plurality of data objects with similar function, then the plurality of objects belong to the same species. With the kind of benefits: we can put the same function with the same type of object data stored in the class, each object without having to repeat a deposit, so just keep each object in its own unique data can be, significant savings in space. So, if the object is a function of the container used to store data, then the category is used to store the same data a plurality of container objects function.

In summary, although we are first introduced after the introductions of the class, but needs to be emphasized: In the program, the class must be defined in advance, then call the class to produce an object (call the class to get the return value is the object). There is a correlation between classes and objects produced objects, this association means: an object can have access to data and functions common to the class, so the content still belongs to the class of object, class is simply a space-saving, reduce code redundancy mechanism for the end of the core of object-oriented programming is still to use the object.

After understanding these two core classes and objects concept, since we can introduce object-oriented programming it.

 

Object-oriented programming three

3.1 class definition of the instance of

We have developed a system of elective Tsinghua University, for example, simply describes how to write programs based on object-oriented thinking

 

Object-oriented basic idea is to use the program, the data associated with the functionality into an object, and then go use, but the program to use the data and function so much, even how to find it? I need to extract the elective system in the role: students, teachers, curriculum, etc., and then apparent that: students with student-related data to function, teachers have teacher-related data and functions, we have a single student, for example,

# 学生的数据有
学校
名字
年龄
性别 # 学生的功能有 选课

detailed

# 学生1:
    数据:
        学校=清华大学 姓名=李建刚 性别=年龄=28 功能: 选课 # 学生2: 数据: 学校=清华大学 姓名=王大力 性别=年龄=18 功能: 选课 # 学生3: 数据: 学校=清华大学 姓名=牛嗷嗷 性别=年龄=38 功能: 选课

We can conclude that a student class, students used to store the same data and functions

# 学生类
    相同的特征:
        学校=清华大学 相同的功能: 选课

 

We then need to do is define a class in a program based on the results of the above analysis, then call the class generated objects

class Student: # 类的命名应该使用“驼峰体”

    school='清华大学' # 数据 def choose(self): # 功能 print('%s is choosing a course' %self.name)

The most common body type is to define the definition of variables and functions, but in fact the class body can contain any Python code, the code will execute in the class body of the class definition stage, and they may be used to store a new name space defined in the class name, you can print Student .__ dict__ like to see this thing in full bloom in the container

>>> print(Student.__dict__) {..., 'school': '清华大学', 'choose': <function Student.choose at 0x1018a2950>, ...}

 

Procedure call is referred to as the class of the instance of the class, it is to get the return value of the object program, known as an example or

>>> stu1=Student() # 每实例化一次Student类就得到一个学生对象 >>> stu2=Student() >>> stu3=Student()

So stu1, stu2, stu3 all as the (only class content are common, but not their unique data), you want an example of the process for the three students to customize their own unique data: name, sex, age, , we need to add a __init__ method within the class, as follows

class Student:
    school='清华大学' #该方法会在对象产生之后自动执行,专门为对象进行初始化操作,可以有任意代码,但一定不能返回非None的值 def __init__(self,name,sex,age): self.name=name self.sex=sex self.age=age def choose(self): print('%s is choosing a course' %self.name)

Then we re-instantiated out of three students

>>> stu1=Student('李建刚','男',28) >>> stu2=Student('王大力','女',18) >>> stu3=Student('牛嗷嗷','男',38)

Take STU1 single generation process to analyze, will first call the class generates an empty object STU1, then STU1 in parentheses with the parameter when invoked with the class passed Student .__ init __ (stu1, 'Li Jiangang', 'M', 28)

def __init__(self, name, sex, age): self.name = name # stu1.name = '李建刚' self.sex = sex # stu1.sex = '男' self.age = age # stu1.age = 28

Will produce the object name space, can also be viewed with __dict__

>>> stu1.__dict__
{'name': '李建刚', 'sex': '男', 'age': 28}

 

At this point, we create three objects with a class, object store each unique data, like stored content objects are shared

 

The purpose of existence is to use, how to access the object or class stored in the content?

 

3.2 property access

3.2.1 class attributes and object attributes

 

Defined in the class name of the class is the attribute, then elaborate, class has two attributes: data attributes and function attributes, can __dict__ access attribute value, such as Student .__ dict __ [ 'school'], but Python provides a special syntax for property access

Illustration: spoof map

>>> Student.school # 访问数据属性,等同于Student.__dict__['school'] '清华大学' >>> Student.choose # 访问函数属性,等同于Student.__dict__['choose'] <function Student.choose at 0x1018a2950> # 除了查看属性外,我们还可以使用Student.attrib=value(修改或新增属性),用del Student.attrib删除属性。

Operating properties of an object is the same

>>> stu1.name # 查看,等同于obj1.__dict__[‘name'] '李建刚' >>> stu1.course=python# 新增,等同于obj1.__dict__[‘course']='python' >>> stu1.age=38 # 修改,等同于obj1.__dict__[‘age']=38 >>> del obj1.course # 删除,等同于del obj1.__dict__['course']

 

3.2.2 property search order and binding method

The name of the object in space only kept the unique properties of the object, and the object have similar attributes are stored in the class. The object, will give priority to look for when you access the properties of the object itself from __dict__, not found, then go to class __dict__ Find

 

1, is a variable defined in the class data class attribute, is shared by all the objects, pointing to the same memory address

# id都一样
print(id(Student.school)) # 4301108704 print(id(stu1.school)) # 4301108704 print(id(stu2.school)) # 4301108704 print(id(stu3.school)) # 4301108704

 

2, the class defined function is a function attribute class, the class may be used, but must follow the rules of function parameters, there are several parameters need to pass several parameters

Student.choose(stu1) # 李建刚 is choosing a course Student.choose(stu2) # 王大力 is choosing a course Student.choose(stu3) # 牛嗷嗷 is choosing a course

But in fact the class defined function is mainly used to target and bind to a target, although all objects are pointing to the same functions, but are bound to different objects is different binding methods, each memory address Not the same

print(id(Student.choose)) # 4335426280 print(id(stu1.choose)) # 4300433608 print(id(stu2.choose)) # 4300433608 print(id(stu3.choose)) # 4300433608

Method to bind to target special is that binding to whoever should call Who, who is called, the 'who' itself as the first argument is automatically passed (__init__ method is the same reason )

stu1.choose()  # 等同于Student.choose(stu1) stu2.choose() # 等同于Student.choose(stu2) stu3.choose() # 等同于Student.choose(stu3)

Bound to choose the skills of different objects, though they are elective, but Li Jiangang selected class, would not choose to Wang Dali, which is "binding" the essence of the word.

#注意:绑定到对象方法的这种自动传值的特征,决定了在类中定义的函数都要默认写一个参数self,self可以是任意名字,但命名为self是约定俗成的。

 

In Python everything is an object, and Python3 class and type is a concept, so we would have come into contact with the binding method

#类型list就是类
>>> list
<class 'list'>  #实例化的到3个对象l1,l2,l3 >>> l1=list([1,2,3]) >>> l2=list(['a','b','c']) >>> l3=list(['x','y'])  #三个对象都有绑定方法append,是相同的功能,但内存地址不同 >>> l1.append <built-in method append of list object at 0x10b482b48> >>> l2.append <built-in method append of list object at 0x10b482b88> >>> l3.append <built-in method append of list object at 0x10b482bc8>  #操作绑定方法l1.append(4),就是在往l1添加4,绝对不会将4添加到l2或l3 >>> l1.append(4) #等同于list.append(l1,4) >>> l1 [1,2,3,4] >>> l2 ['a','b','c'] >>> l3 ['x','y']

 

3.3.3 Summary

In the introduction class and object use, the more we are standing on the underlying principle of perspective to introduce the relationships between classes and objects, if only to stand in the perspective of use, we need to consider grammar "Object Property" "properties" in the end comes from where, just need to know is to get through the object on it, so that the object is a highly integrated product, with the object, we just need to use the syntax "Object .xxx" would you can get all the data and functions associated with this object, the solution is very convenient and extremely high degree of coupling.

 

Guess you like

Origin www.cnblogs.com/heirenxilou/p/12654303.html