Python object-oriented attributes and class methods (6)

Class attributes and class methods

aims

  • Class structure
  • Class attributes and instance attributes
  • Class methods and static methods

01. The structure of the class

1.1 Terminology-Examples

1. Using object-oriented development, the first step is to design the class

2. Use the class name () to create an object. There are two steps in creating an object:

  1. Allocate space for objects in memory
  2. Call the initialization method _ init _ to initialize the object

3. After the object is created, there is a real existence of the object in the memory-an instance
Insert picture description here

Therefore, usually:

  • The created object is called an instance of the class
  • The action of creating an object is called instantiation
  • Object properties are called instance properties
  • The method called by an object is called an instance method

When the program is executed:

  • Each object has its own instance attributes
  • Call object methods, you can
    access your own properties through self.
    Call your own methods

in conclusion

  • Each object has its own independent memory space and saves different attributes
  • The method of multiple objects has only one copy in memory. When calling the method, the reference of the object needs to be passed into the method.

1.2 A class is a special object

  • Everything in Python is an object:
    class AAA: The defined class belongs to the class object
    obj1 = AAA() belongs to the instance object
  • When the program is running, the class will also be loaded into memory
  • In Python, a class is a special object-class object
  • When the program is running, there is only one copy of the class object in memory, and many object instances can be created using one class
  • In addition to the properties and methods of packaging instance, class objects may also have its own properties and methods
    class attributes
    class method
  • You can access the properties of the class or call the methods of the class through the class name.
    Insert picture description here

02. Class attributes and instance attributes

2.1 Concept and use

  • The class attribute is the attribute defined in the class object
  • Usually used to record the characteristics related to this class
  • Class attributes will not be used to record the characteristics of specific objects

Example requirements

  • Define a tool class
  • Each tool has its own name
  • Requirements-know how many tool objects are created using this class?
class Tool(object):# 使用赋值语句,定义类属性,记录创建工具对象的总数
   count = 0def __init__(self, name):
       self.name = name
​
       # 针对类属性做一个计数+1
      Tool.count += 1
​
​
# 创建工具对象
tool1 = Tool("斧头")
tool2 = Tool("榔头")
tool3 = Tool("铁锹")# 知道使用 Tool 类到底创建了多少个对象?
print("现在创建了 %d 个工具" % Tool.count)

2.2 Attribute acquisition mechanism (Science)

There is an upward lookup mechanism for obtaining attributes in Python
Insert picture description here

Therefore, there are two ways to access class attributes:

  • Class name. Class attributes
  • Object. Class attributes (not recommended)

Note that
if you use the object. class attribute = value assignment statement, only one attribute will be added to the object, and the value of the class attribute will not be affected

03. Class methods and static methods

3.1 Class methods

  • Class attributes are attributes defined for class objects.
    Use assignment statements to define class attributes under the class keyword. Class attributes
    are used to record characteristics related to this class.
  • Class methods are methods defined for class objects.
    In class methods, you can directly access class attributes or call other class methods.

The syntax is as follows

@classmethod
def 类方法名(cls):
   pass
  • The class method needs to be identified by the decorator @classmethod to tell the interpreter that this is a class method
  • The first parameter of the class method should be cls
  • The method called by which class, the cls in the method is the reference of which class
  • This parameter is similar to the first parameter of the instance method, which is self
  • Prompt that other names can be used, but I am used to using cls

1. Call the class method through the class name. When calling the method, there is no need to pass the cls parameter.
2. Inside the method

  • The properties of the class can be accessed through cls.
  • You can also call other class methods through cls.

Example requirements

  • Define a tool class
  • Each tool has its own name
  • Requirements-encapsulate a show_tool_count class method in the class, and output the number of objects created using the current class
    Insert picture description here
@classmethod
def show_tool_count(cls):
   """显示工具对象的总数"""
   print("工具对象的总数 %d" % cls.count)

Inside the class method, you can directly use cls to access class attributes or call class methods

3.2 Static method

  • During development, if you need to encapsulate a method in a class, this method:
    neither need to access instance properties or call instance methods
    nor need to access class properties or call class methods
  • At this time, you can encapsulate this method into a static method. The
    syntax is as follows
@staticmethod
def 静态方法名():
   pass
  • The static method needs to be identified by the decorator @staticmethod to tell the interpreter that this is a static method
  • Pass the class name. Call the static method
class Dog(object):
   
   # 狗对象计数
   dog_count = 0
   
   @staticmethod
   def run():
       
       # 不需要访问实例属性也不需要访问类属性的方法
       print("狗在跑...")def __init__(self, name):
       self.name = name

3.3 Comprehensive case of method

demand

  • Design a Game class
  • Attribute:
    Define a class attribute top_score to record the highest score in the game's history.
    Define an instance attribute player_name to record the name of the player in the current game
  • Method:
    static method show_help displays game help information.
    Class method show_top_score displays the highest score in history.
    Example method start_game starts the current player’s game.
  • Main program steps
  1. View help information
  2. View the highest score in history
  3. Create a game object and start the game
    Insert picture description here

Case summary

  • Instance method-inside the method needs to access the instance attribute
    . The inside of the instance method can use the class name. Access to the class attribute
  • Class method-only need to access class attributes inside the method
  • Static method-inside the method, there is no need to access instance attributes and class attributes

If the method needs to access the instance attribute and the class attribute, what method should be defined?

Instance method should be defined

Because there is only one class, the class name can be used inside the instance method. Access to class properties

class Game(object):# 游戏最高分,类属性
   top_score = 0
​
   @staticmethod
   def show_help():
       print("帮助信息:让僵尸走进房间")
       
   @classmethod
   def show_top_score(cls):
       print("游戏最高分是 %d" % cls.top_score)def __init__(self, player_name):
       self.player_name = player_name
​
   def start_game(self):
       print("[%s] 开始游戏..." % self.player_name)
       
       # 使用类名.修改历史最高分
       Game.top_score = 999# 1. 查看游戏帮助
Game.show_help()# 2. 查看游戏最高分
Game.show_top_score()# 3. 创建游戏对象,开始游戏
game = Game("小明")
​
game.start_game()# 4. 游戏结束,查看游戏最高分
Game.show_top_score()

Guess you like

Origin blog.csdn.net/weixin_42272869/article/details/113695937