Core syntax - python--Class 01

Core syntax - python - Class 01

#1. Class definition

Class name (inherited class):

**Statement block (also known as "class body", including class member definitions, attributes and methods)**

Among them,
Class - keyword, indicating the beginning of the definition class
Inherited classes - also known as "base classes", can be one or more, and are the father of the class. In general, if an appropriate class is inherited every day, the object class is often used, which is the base class that all classes will eventually inherit.
In other words, object is the father of all classes.
Class name - it can be taken as long as it complies with the identifier naming rules. Usually, the first character is capitalized, which is different from other functions or methods to indicate that it is a class name.
Statement block (class body) - concrete code that defines the properties and methods of this class. If the statement block is empty, pass is recommended. This is strongly recommended by Python because the python language does not have the empty statement ";" similar to that in C and C + + languages. The statement pass is an empty statement in Python language. It has three functions: it represents empty statement (do nothing); Ensure that the format is complete; Ensure semantic integrity.

#2. Examples of class definitions
#Example 1: define a student class 1

class student(object):
    pass

The above code defines a class named "student", but it has neither properties nor methods, so it is an empty class, and its parent class is object

class Student:
    pass

The above code also defines a class called "Student". In Python 3, if "(object)" is omitted after the class name, the Python interpreter will automatically supplement it. The above two classes are actually the same, empty class.

#Example 3: add properties to an instance created by an empty class

class Student(object):
    pass

#Instantiation

st1 = Student()       #Generate an instance (object st1) through Student()
#Add properties to an instance
st1.name = "Jack Ma"   #Set the instance's property name
st1.age = 18       #Set the properties of the instance
print(st1.name)    #Displays the properties of the instance
print(st1.age)

#Instantiation 2

st2 = Student()
print(st2.name) #No attribute added, so error!

"""
Traceback (most recent call last):
  File "D:/Python/pycharm/pycharm_code/Class_Python.py", line 47, in <module>
    print(st2.name)
AttributeError: 'Student' object has no attribute 'name'
"""

For the above class, the attribute of the class is not added when defining the class, but added outside the class. For the instantiated class, add attributes to be valid for the instance. If you do not add a property, the instance will not have this property.

#Define a Gamer class (Gamer)

class Gamer(object):

    """
    Game player

    #This block is the document string of the class, which is used to describe the class. Can be used for "class name. _ doc _". Can be written or not. It is recommended to write it for easy understanding of the code
    """
    #Constructor to initialize an instance of the class
    def __init__(self,number,name,sex):
        self.name = name
        self.number = number
        self.sex = sex
        self.score = 0
    """
    def __init__(self)modular:
        Class, equivalent to constructors in other languages;
        It is used to initialize instances of a class and is automatically called when creating instances. It is used to set the properties of all instances;
        The first parameter must be self ´╝îOther parameters depend on the needs of the class;
        Optional, but usually required. This method cannot have return sentence
    """
    #How to start the game
    def start_game(self):
        print("{}Start the game...".format(self.name))

    #Case scoring method
    def add_score(self,score):
        self.score += score

    #Get instance score method
    def get_score(self):
        return self.score
"""
The above is an instance method of the class
 Used to set the properties and behavior of the instance;
The first parameter must be self.Other parameters depend on the needs of the class;
The number of methods is unlimited and can be determined as needed. For example, this example has three instance methods;
The essence of a method is a function. The syntax related to a function is applicable to methods, such as default parameters, keyword parameters, list and dictionary parameters, indefinite length parameters, etc.
"""

"""
The inherited class (parent class) of the above Gamer class is object, which is the default base class of the system. This class currently defines four instance attributes: name, number, sex and score,
It is used to set the name, number, gender and score of each instance respectively.
This class defines three instance methods: start_game(),add_score() and get_score() is used to start the game, score and get a score.
Class is mainly used to set the behavior of the instance. The first parameter of the method must be self, which represents the instance itself, but it is not necessary to pass this parameter when calling.
"""

#init() method

The init() method, also known as the "constructor", has the following four features.
(1) This method is very special. There is a double underscore "_ before and after init. Its first parameter must be self, which has the same meaning as other methods. Other parameters are used to set the properties of instances, and the number is unlimited. This method cannot use return.
(2) The init() method can be defined anywhere in the class.
(3) This method is automatically called once when a new instance is created by the class. That is, the method will be called once every instance is created.
(4) This method is commonly used to define the properties of an instance, but defining the properties of an instance is not limited to this method. In other words, the properties of an instance can also be defined in other methods.

class Gamer(object):
    """
    Gamer class
    So and so
    """
    top_score = 0  #Class variable to save the highest score in history
    games = 0 #Number of players
    """
    #Class. It is a static variable
    #It is used to set the related common properties of the class and is referenced by the class
    #Both inside and outside the class are available. Reference method: class name. Variable name
    """
    #Static method
    @staticmethod
    def show_help():  #Methods that do not require class variables and instance variables
        print("This is a guessing game (1)-100 Integer)")
        print("You can have three players at the same time")
        print("Who is closest and who scores the highest")
        print("10 points for accuracy")
        print("Error as early as 10%Within 8 points, 20 points%6 points")
        print("The error is 30%Within 5 points, otherwise no point will be given")
    """
    Class. It belongs to class and is referenced by class
    In the first line of the method definition, through the decorator@staticmethed Declare that the method defined next on the surface is a static method;
    Parameters are optional. No implicit parameters passed in
    Both inside and outside the class can be referenced. Both classes and instances can be referenced
    """
    #Class method
    @classmethod
    def show_top_score(cls):  #Displays the highest score in history
        print("What is the highest score in the game%d"%cls.top_score)
    @classmethod
    def show_games(cls):      #Displays the number of gamers
        print("Total gamers %d people"%cls.games)
    """
    Class method
    The first parameter must be cls. Other production parameters depend on the needs of the class;
    Both inside and outside the class can be referenced. Both classes and instances can be referenced
    """
    #Constructor
    def __init__(self,number,name,sex):
        self.name = name   #Instance attribute: name
        self.number = number   #Instance attribute: number
        self.sex = sex  #Instance attribute: sex
        self.score = 0 #Instance attribute: score
        Gamer.games += 1  #Number of players + 1

    #How to start the game
    def start_game(self):
        print("{}Start the game...".format(self.name))

    #Case scoring method
    def add_score(self,score):
        self.score += score

    #Get instance score method
    def get_score(self):
        return self.score
"""
The above three example methods
 Class
 The first parameter must be self. Other parameters depend on the needs of the class;
In class and out of class references. Only instance references;
Intra class reference: self.method
 Out of class References: instances.method
"""
"""
Class variable--Static variable
 Attribute Variable--Dynamic variable
 General variable--Dynamic variable, an intermediate variable within a method
 Class method, static method, instance method
"""

Tags: Python AI

Posted on Tue, 23 Nov 2021 02:54:43 -0500 by web_noob