Simple Python object-oriented tutorial

Preface

The text and pictures in this article are from the Internet and are for learning and communication purposes only. They do not have any commercial use. If you have any questions, please contact us for processing.

PS: If you need Python learning materials, you can click on the link below to get it yourself

Python free learning materials and group communication answers Click to join


Instance attributes and class attributes

In the following example, the attributes of the Dog class, such as height, belong to a specific dog, such as rhubarb, two black, etc. They each have their own height.

This kind of attribute is called instance attribute , which is usually created in the init method through self.xxx = yyy . The advantage of the instance attributes created in init is that all instances have these instance attributes.

You can also add an additional instance name in the subsequent code, such as d1.nickname ='二黑子' , but this instance attribute is only added to the current instance d1. No other instances, access to d2.nickname will report an error.

class Dog:
 #构造方法
 def __init__(self, name, height, power):
  self.name = name
  self.height = height
  self.power = power
  self.blood = 10
  # --省略--

d1 = Dog('大黄', 0.7, 3) #创建第1个实例
d2 = Dog('二黑', 0.5, 4) #创建第2个实例

There are also some attributes that do not belong to a specific instance, but are shared by all instances. For example, the value of the number of dogs belongs to the entire dog category, not to a certain dog. This kind of attribute is called class attribute.

Add class attributes

We now add the number of dogs attribute (num_of_dogs) to the Dog class.

Class attributes cannot be created in the form of self.xxx = yyy, because this creates instance attributes.

The method of creating class attributes is very simple: write directly in the class, do not write in the init function, and do not add self.:

#类是一个模板
class Dog:
 num_of_dogs = 0  # 类属性

 #构造方法 - 添加实例属性,做其他的初始化工作
 def __init__(self, name, height, power):
        self.name = name
        self.height = height
        self.power = power
        self.blood = 10
        print(f"{self.name}出生了,汪汪!")

Use class attributes

The class attribute belongs to the class, and access to the class attribute is through the class name. The following code does several things:

1. In the init function, once a new Dog is created, add one to num_of_dogs.
2. A die() method is added to indicate that a Dog has passed away. Once die() is called, num_of_dogs will be reduced by 1.
3. Create multiple dogs, test the number of numer_of_dogs changes; loop 30 times, randomly select a Dog, and call the die method.
The random module random is used here, as well as the addition (+=) and subtraction (-+) operators. If you are not familiar with it, please add relevant knowledge yourself or join the discussion group for discussion.

import random

#类是一个模板
class Dog:
    num_of_dogs = 0  # 类属性

 #构造方法 - 添加实例属性,做其他的初始化工作
    def __init__(self, name, height, power):
        self.name = name
        self.height = height
        self.power = power
        self.blood = 10
        print(f"{self.name}出生了,汪汪!")
        Dog.num_of_dogs += 1
    
    def die(self):
        print(f"{self.name}已安息!")
        Dog.num_of_dogs -= 1

# 创建100条狗,放到列表中
dogs = []
for i in range(100):
    d = Dog(f"dog{i}", random.randint(30, 80), random.randint(1,12))
    print(Dog.num_of_dogs)
    dogs.append(d)

# 循环30次,每次随机选择一条狗,让它死掉
for i in range(30):
    dog = random.choice(dogs)
    dog.die()
    print(Dog.num_of_dogs)

Add 1 more class attribute

Suppose we want to determine whether a dog can be a police dog, we use height to determine if the height exceeds 60. This 60 is the standard for police dogs. This number is common to all Dogs and is a class attribute.

import random

#类是一个模板
class Dog:
    num_of_dogs = 0  # 类属性
    police_height = 60 # 成为警犬的身高标准

    # --省略init和die方法

    # 判定是否可以成为警犬,返回True或者False
    def can_be_police(self):
        return self.height > Dog.police_height

# 创建100条狗,放到列表中
dogs = []
for i in range(100):
    d = Dog(f"dog{i}", random.randint(30, 80), random.randint(1,12))
    print(Dog.num_of_dogs)
    dogs.append(d)

print(f'成为警犬的身高标准是:{Dog.police_height}')
for d in dogs:
    if(d.can_be_police()):
        print(f'{d.name} 可以成为警犬')

Code description:

  • Added a police_height class variable
  • Added an instance method to determine whether the current dog can become a police dog
  • At the bottom of the code, print the name of a dog that can become a police dog

Code practice skills

You might be thinking, can't this 60 be written directly in the code? Also defined as a variable?

It is not impossible to write the number 60 directly, but there are many drawbacks:

  • Used in multiple places, it may be wrong and inconsistent.
  • If the standard is raised from 60 to 62, many places will be revised
  • Defined as a variable, the code is easier to understand. Otherwise, if you see the number 60, you may not understand what it means.

In fact, polic_height usually does not change, we can also call it a constant.
There is no difference between a constant and a variable. Generally, the names of constants are all uppercase, nothing more. When you see all capitals, you know that this value will not change, but it can actually be changed, just a convention.

The term “unchanged” here means that it will not change dynamically while the program is running. Changing the value of a constant from 60 to 62 is a modification of the code, and it can be done at any time.

Class method

Take a closer look at the previously defined methods, they all have two characteristics:

  • The first parameter of the method is self
  • They all use instance variables and are separated from specific instances. These methods cannot be run and are meaningless.

Although these methods are common, their running process relies on instance variables, so they are all instance methods. The methods in the class are instance methods by default.

import random

#类是一个模板
class Dog:
    num_of_dogs = 0  # 类属性
    police_height = 60 # 成为警犬的身高标准

 #构造方法 - 添加实例属性,做其他的初始化工作
    def __init__(self, name, height, power):
        self.name = name
        self.height = height
        self.power = power
        self.blood = 10
        print(f"{self.name}出生了,汪汪!")
        Dog.num_of_dogs += 1
    
    def die(self):
        print(f"{self.name}已安息!")
        Dog.num_of_dogs -= 1

    # 判定是否可以成为警犬,返回True或者False
    def can_be_polic(self):
        return self.height > Dog.police_height

These three methods are all related to instance attributes, and they are all instance methods.

But some methods have nothing to do with specific examples, but with the whole dog. For example, there is a method dog declaration, its function is:

  • Print dog declaration
  • Introduce the number of dogs

Look at the code:

import random

#类是一个模板
class Dog:
    num_of_dogs = 0  # 类属性
    police_height = 60 # 成为警犬的身高标准

    #--省略--
    
    # 类方法
    @classmethod 
    def wangwang(cls):
        print('我们是狗,我们是人类的朋友')
        print('''
^..^      /
/_/\_____/
/\   /\
/  \ /  \
        ''')
        print(f'我们共有{cls.num_of_dogs}个成员')

# --省略--    

Dog.wangwang()

Code description:

  • Added class method wangwang()
  • Add before the class method: @classmethod. This is a decorator.
  • The first parameter of the class method is cls, which is the abbreviation of class and represents the current class. Use cls to access class attributes or other class methods.
  • Call the class method using the class name: Dog.wangwang()

Static method

We can see that class methods depend on class attributes. Some methods have no dependency on instance attributes and class attributes, and do not need to pass in self or cls. These methods are static methods.

Suppose we have several other methods: just print the character drawing of the dog, without printing the number of dogs or other. There is no dependency on class attributes or instance attributes.

Look at the code:

import random

#类是一个模板
class Dog:
    num_of_dogs = 0  # 类属性
    police_height = 60 # 成为警犬的身高标准

    # --省略--
    
    # 类方法
    @classmethod 
    def wangwang(cls):
        print('我们是狗,我们是人类的朋友')
        print('''
^..^      /
/_/\_____/
/\   /\
/  \ /  \
        ''')
        print(f'我们共有{cls.num_of_dogs}个成员')

    #静态方法:小狗的图像
    @staticmethod
    def pic_little():
        print('''
  /^ ^\ 
 / 0 0 \ 
 V\ Y /V
  / - \ 
 /    |
V__) ||
        ''')

    #静态方法:大狗的图像
    @staticmethod
    def pic_big():
        print('''
    ___
 __/_  `.  .-"""-.
 \_,` | \-'  /   )`-')
  "") `"`    \  ((`"`
 ___Y  ,    .'7 /|
(_,___/...-` (_/_/ 
        ''')
    
    #静态方法:长的图像
    @staticmethod
    def pic_long():
        print('''
                                    .-.
     (___________________________() `-,
     (   ______________________   /''"`
     //\\                      //\\
     "" ""                     "" ""

        ''')


#--省略--

Dog.wangwang()
Dog.pic_little()
Dog.pic_big()
Dog.pic_long()

Code description:

  • Added 3 static methods to print 3 different dog images
  • The static method must be preceded by: @staticmethod, which is a decorator.
  • Static methods do not require self or cls to be passed in.
  • Call the static method by the class name.

Guess you like

Origin blog.csdn.net/pythonxuexi123/article/details/112849702