Advanced Python ----- Object-Oriented 1.0 (Introduction and Definition of Objects and Classes)

Table of contents

Foreword:

procedural and object oriented

classes and objects

Class definition in Python

(1) Class definition form

(2) Deep analysis of class objects


Foreword:

      Thank you for your company all the way. I have been learning Python for a month. During this month, I have gained a lot and learned a lot of knowledge. Whenever I learn a new knowledge point, I will publish a blog to express my thoughts and opinions. I also wrote a column on Python basic learning ( https://blog.csdn.net/m0_73633088/category_12186491.html ) This stage of learning has basically come to an end, and today I will start learning Python The advanced syntax of Python starts a new journey of advanced Python. The road is long and difficult, but I keep going forward.

procedural and object oriented

        Programming languages ​​are generally divided into two programming paradigms, one is process-oriented, and the other is object-oriented. These two paradigms are different language methods, and the emphasis is completely different.

Process-oriented: The Python basic grammar and C language we learned earlier are process-oriented grammars, and their core lies in the word process. Process refers to the steps to solve the problem. When programming, first analyze the steps to solve the problem , and then use functions to implement these steps, and then call the functions in order in the specific steps step by step, which is suitable for simple tasks and does not require too much collaboration.

Object-oriented: The core is the word object . Objects are composed of attributes and methods. When programming, the first thing to think about is how to design this thing. For example, when thinking about building a car, we will think about how to design a car? , instead of "how to build a car according to the steps", find a tire factory to manufacture tires, and an engine factory to manufacture engines, and find that the steps of simultaneous car manufacturing are combined to complete car manufacturing, which greatly improves efficiency. Object-oriented is the essence of Python language.

         Then someone will ask here: These two programming paradigms must be different. It should be that object-oriented is more advanced than process-oriented. attention! ! ! There is no distinction between high and low programming paradigms , just like culture. Why do some people always worship foreigners? Is Chinese culture inferior? Is Chinese Hanfu not good-looking? Why do you have to wear a kimono? Come on, Chinese culture has a history of 5,000 years. It has a long history and is profound enough to be proud of the whole world! Here is just to explain that the programming paradigm is the same as the culture. In fact, there is no distinction between high and low, but the adaptability in different situations is different. Don't have any prejudice.

classes and objects

Classes: That's it for classes, okay, so what is a class? In fact, it is very simple to understand. For example, a species, or a certain type of people, as the name implies, " category" means that a certain kind of thing has a certain common feature, which can be divided into one category

Object: An object represents an example of this class and is a specific instance (concrete existence)

Let’s give an example: For example, dogs can be divided into many breeds. Take huskies and golden retrievers as objects. What attributes does huskies have? I don’t need to say this, Erha’s names are all there; what attributes does the golden retriever have? Relatives, docile personality, considerate to others, these are the unique attributes of these two objects, and the attributes they have in common are: can bark, do bad things, wag their tails... and so on. It's easy to understand! ! !

Class definition in Python

We have learned that the type of string is str, the type of integer is int, the type of floating point is float... etc. These are all defined classes in Python. We can use these classes to call the class inside the class. Attributes and methods, then here I will teach you how to define classes and how to understand classes

(1) Class definition form

We have learned before that the definition of a function is def + function name: The following is the function body. In fact, the class is similarly defined with the keyword class :

#函数的定义
def 函数名(形参):
    函数体
    
函数名(实参)

#类的定义
class 类名:
    类代码(属性,方法)

Class related rules:

Definition of class name: Named with big hump, (all words are capitalized)

There is no instance object after the class is defined: execute the code, and the code in the class is executed

Variables defined in a class are called attributes, and functions are called methods

Example 1: Defining and modifying class attributes 

class Dog:
    name='dog' #在类中的变量是属性(attribute)
    age=5
erha=Dog() #建立实例化对象
print(type(erha))
#输出结果:dog 5
#  <class '__main__.Dog'>

 Explanation: Here is to create a Dog type, which has two attributes, name and age. These two class attributes are common attributes of instantiated objects. Below we create a substantive object erha=Dog() and then we will The properties of this materialized object can be output, and its type is the Dog type, which is easy to understand here

class Dog:
    name='dog' #在类中的变量是属性(attribute)
    age=5
erha=Dog()
print(erha.name,erha.age)
erha.age=3
erha.name='gou'
print(erha.name,erha.age)
#输出结果:
# dog 5
# gou 3

The class attribute of the instantiated object can be modified, and it is OK to directly assign and modify 

Example 2: Defining instance methods

1. Writing 1

class Dog:
    name='dog'
    age=5
    def fun(self):
        print('这是一直可爱的小狗')
erha=Dog()
print(erha.fun())
#输出结果:这是一直可爱的小狗

2. Writing method 2:, through class name. method (instance object) --- expression

#写法:
class Dog:
    name='dog'
    age=5
    def fun(self):
        print('这只小狗真可爱')
erha=Dog()
print(Dog.fun(erha)) #我们可以直接把实例参数传入到self
#输出结果:这只小狗真可爱

3. Add positional parameters

class Dog:
    name='dog'
    age=5
    def fun(self,name): #定义参数name
        print(f'这是一直可爱的小狗{name}')
erha=Dog()
print(Dog.fun(erha,'happy'))
#输出结果:这是一直可爱的小狗happy

 Notice:

An instance method is defined here as fun, so someone here will ask, isn't this just a function? No, in Python, what is defined in a class is not called a function, but a method, and what is defined outside a class is called a function, which needs to be distinguished here.

 illustrate:

This is an instance method. A self parameter is automatically created during the creation process. This parameter represents the instance object itself. When we create an object, we can call this method. The above are the three ways of writing this method call

Example 3: init initialization method

  • init initialization method is also called instantiation method, magic method, construction method

  • This method is automatically called when the (instance) object is initialized, and is usually used to initialize the properties of the object

  • This method is automatically called when the object is instantiated and does not need to be called manually

class Dog:
    animal='dog'
    def __init__(self,name,age): #name和age是表示实例对象的初始化属性,也是特定属性
        self.name=name  #这里的self.name是自己定义的,而后面的name是参数
        self.age=age
    def fun(self):
        print('这只小狗真可爱')
if __name__=='__main__':
   erha=Dog('Timi',5) #里面的参数必填,否则会报错
   print(erha.animal,erha.name,erha.age)
   print(erha.__dict__) #查看实例对象erha 的特定属性
#输出结果:dog Timi 5
#         {'name': 'Timi', 'age': 5}

The init initialization method is to define and initialize the characteristic attributes of the instance object. We can check it through __dict__, and then return the key-value pairs of the instance object attributes.

(2) Deep analysis of class objects

class Dog:
    name='dog'
    age=5
print(Dog)
erha=Dog()
print(id(erha))#输出获取地址
#输出结果:<class '__main__.Dog'>
#         2931955054960

Here we can see that when we call, we need to add (), which is the same as the function. If we don’t call it, it will be the same as the first output result, outputting the type of this class, for example: print(int ) The output of this is <class 'int'>. When we call this class, we have actually created a substantive object. At this time, the computer will open up a section of memory space, and the address obtained from the id() function can be see

Let's look at another example: 

class Dog:
    name='dog'
    age=5
erha=Dog()
print(id(int))
print(id(Dog))
print(id(erha))
#输出结果:140735865654544
#         2504339459136
#         2505947003248

 Here we can see that the class itself has a space address, and when we create an instantiated object, we actually create a class pointer. The class pointer of this object erha points to the Dog type. We can pass this class This also shows that if I define multiple instance objects, the class pointers of these instance objects will point to the defined class Dog, so a class has public functions.

class Dog:
    animal='dog'
    def __init__(self,name,age):
        self.name=name
        self.age=age
    def fun(self,name):
        print(f'这只{name}真可爱')
    def recurrence(self,age):
        i=1
        sum=1
        while i<=age:
            sum*=i
            i+=1
        return sum
if __name__=='__main__':
    erha=Dog('哈士奇',5)
    Dog.fun(erha,erha.name)
    print(Dog.recurrence(erha,erha.age))

    jinmao=Dog('金毛',4)
    Dog.fun(jinmao,jinmao.name)
    print(Dog.recurrence(jinmao,jinmao.age))
#输出结果:这只哈士奇真可爱
#         120
#         这只金毛真可爱
#         24

It can be seen here that I have created two instance objects, the methods of which are shared, which also shows the power of class pointers.

Well, this is the end of this issue, thank you~~~

Share wallpapers every day~

 

Guess you like

Origin blog.csdn.net/m0_73633088/article/details/129259110