Core syntax Python--Class syntax 02

Core syntax Python – Class 02

Instance variables and class variables

There are two types of variables related to Python classes: instance variables and class variables. In addition, some intermediate variables may be used in the instance method. These intermediate variables can only be used in an instance method. They are ordinary variables. Global variables can be used in all instances.

1. Instance variable
The non ordinary variable defined in the instance method is the instance ratio, also known as "instance attribute". The instance variable can be called by the method that defines it or by other methods in the class. The calling form is: self. Variable
Instance variables cannot only be__ init__ () defined by the method.
For example, in the Gamer class, four instance variables are defined: the variable name representing the name, the variable number representing the number, the variable sex representing the gender, and the variable score representing the score. They are all constructed by the constructor
(initialization method) defined by init(). Of course, in other instance methods, instance variables can also be defined.
As follows:

class Mm(object):
    def __init__(self,name):
        self.name = name

    def setmm(self,age):
        self.age = age
    def show(self):
        print(self.name,self.age)
a1 = Mm('shh')
a1.setmm(34)
a1.show()
print(a1.name,a1.age)

In the above example, two instance variables - name and age are defined in two different ways. Instance variables can be referenced by instances within or outside a class. There are two methods to reference instance variables:
The first method refers to the instance variable in the class. Its syntax form is: self. Instance variable
For example: self.name = "Zhang Junying"
The second method refers to the instance variable outside the class. Its syntax form is: instance. Instance variable
For example, a1 = Gamer('101 ',' Junying ', 20)
a1.score += 10
2. Class variable
The so-called "class variable" refers to the variable defined separately in the class, but not in any method of the class. It is also called "class attribute", which is different from the instance attribute. For example, the two variables top defined in the Gamer class_ Score and games are class variables.
Class variables can be shared by all instances of a class.
Class variables are often not referenced as frequently as instance variables.
Class variables can be referenced by classes inside or outside the class, but class variables can only be referenced by classes. The method of referencing class variables is as follows:
(1) Intra class reference intra class variable syntax: cls. Class variable
cls.gamers +=1
(2) Syntax for referencing class variables outside a class: class. Class variables
a1 = Gamer('101','Junying',20)
Gamer.gamers += 1

3. Relationship between instance variables and class variables
The relationship between instance variables and class variables is as follows:
(1) Instance variables are owned by each instance, and the instance variables of each instance are independent of each other; Class variables can only be owned by classes.
(2) If the instance variable has the same name as the class variable, the instance variable takes precedence over the class variable. Therefore, instance variables mask class variables. In other words, instance variables are used first.

Private properties and private methods
1. Private properties and methods
If a property or method name begins with a double underscore "_", the property or method cannot be accessed outside the class. They are called private properties and private methods
2. Built in properties and methods
If a property or method is defined in the form of "xxx", that is, there are double underscores before and after, the property or method can be accessed outside the class. In Python classes, attributes and methods defined in the form of "xxx" are special attributes and special methods,
They are called built-in properties and built-in methods.
In general, do not define common attributes in the form of "xxx",
Python has ordered several special properties and methods. All Python classes have the following built-in properties and can be accessed like any other property.
dict: dictionary containing the namespace of the class
doc: dictionary containing the namespace of the class
Name: class name
mmodule: defines the module name of the class. Under this attribute, the value in interactive mode is "main"
__ bases: a tuple containing a base class. Tuple elements are arranged in the order in which they appear in the base class list.

Private property case
A property that begins with a double underscore is private, so it cannot be used or accessed directly outside the class.

class Mytester(object):
    def __init__(self,dat1,dat2):
        self.__dat1 = dat1   #Private property
        self.dat2 = dat2
    def get_dat1(self):
        return self.__dat1

if __name__ == '__main__':
    test1 = Mytester(10,18)
    print(test1.dat2)
    """
    print(test1.__dat1)
      File "D:\Python\pycharm\pycharm_code\Class_Python02.py", line 120, in <module>
    print(test1.__dat1)
AttributeError: 'Mytester' object has no attribute '__dat1'
    """
    print(test1._Mytester__dat1)
    print(test1.get_dat1())
    print(test1.__dict__)

There are two ways to access private properties outside the class:

1,
Change print (test1. _dat1) to print (test1. _mytester_dat1)
2,
Change print (test1. _dat1) to print(test1.get_dat1())

Private properties cannot be inherited
How to view all properties

print(test1.__dict__)

Although private properties can be accessed outside the class, do not access them. It can be considered that private properties cannot be accessed directly outside the class. Just remember!

Private method

class Person(object):
    def __init__(self):
        self.__name ='Zhang San'    #Private property
        self.age = 22
    def __get_name(self):      #Private method
        return self.__name

    def get_age(self):          #public Method 
        return self.age
if __name__ == '__main__':
    p1 =Person()
    print(p1.get_age())
 
 """
    print(p1.__get_name())
    Traceback (most recent call last):
  File "D:\Python\pycharm\pycharm_code\Class_Python02.py", line 154, in <module>
    print(p1.__get_name())
AttributeError: 'Person' object has no attribute '__get_name'
"""

It is recommended that you do not use private properties and private methods outside your class

Use of classes

Classes without default properties and their use
Create a class:
Object 1 = class (parameter 1, parameter 2,...)

Access the properties of the instance or class and call the methods of the instance or class in the following forms.
(1) The form of accessing instance properties is: object. Instance properties
(2) The form of accessing class attributes is: class. Class attribute
(3) The form of calling instance method is: object. Instance method
(4) The form of calling class method: class. Class method or class. Class static method

#case
class Gamer(object):
    """
    Gamer
    So and so
    """
    top_score = 0   #Class variable
    gamers = 0

    #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("If it is exactly the same, 10 points will be given, with an error of 10 points%Within 8 points, 20 points%6 points")
        print("The error is 30%Within 5 points, otherwise no point will be given")

    #Class method
    @classmethod
    def show_top_score(cls):
        print("The highest score of the game is:%d"%cls.top_score)
    @classmethod
    def show_gamers(cls):
        print("Total gamers:%d"%cls.gamers)

    def test():
        print("kkkk")

    #Constructor (initializing an instance of a class)
    def __init__(self,number,name,sex):
        self.name = name
        self.number = number
        self.sex = sex
        self.score = 0
        Gamer.gamers += 1

    #How to start the game
    def start_game(self):
        self.age = 16
        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):
        # self.add_score(s)
        return self.score

Gamer.show_help()  #Call class method
a1 = Gamer("101",'Junying',18)   #Create instance a1
a1.start_game()                         #Call instance method
a1.add_score(10)
print(a1.get_score())
print(a1.add_score(10))
print(a1.get_score())
print(Gamer.gamers)
a2 = Gamer('102','Yd',19)
Gamer.show_top_score()
Gamer.show_gamers()
a1.age          #Access instance properties

print(Gamer.__dict__)
print(Gamer.__doc__)
print(Gamer.__module__)
print(Gamer.top_score)

Classes with default properties and their use
When defining a class, you can set default values for instance properties. If the actual parameters are omitted when the method is called, the corresponding instance properties are set to the default values.

class Food(object):
    """
    Takeout
    #Attributes: customer, address, mobile phone number, number of copies, discount

    """
    def __init__(self,name,address,moblile,discount=1):  #No discount by default
        self.name = name
        self.address = address
        self.mobile = moblile
        self.discount = discount

    #Cost calculation method
    def cacl_all(self,servings=1):  #The number of copies is 1 by default
        return servings*10*self.discount
if __name__ == '__main__':
    #Customer 1
    name = input("Welcome Junying Dumpling restaurant! Hello, your name:")
    mobile = input("May I have your mobile number")
    address =input("May I have your address")
    servings = int(input("How many copies:"))

    c1 = Food(name,address,mobile) #Create instance
    print("Number of copies:{}cost:{}".format(servings,c1.cacl_all(servings)))

    #Customer 2
    name = input("Welcome Junying Dumpling restaurant! Hello, your name:")
    mobile = input("May I have your mobile number")
    address = input("May I have your address")
    servings = int(input("Number of copies:"))

    c2 = Food(name,address,mobile,0.95)  #5% off
    print("Number of copies:{}cost:{}".format(servings,c2.cacl_all(servings)))

Combination of classes

#Combination of classes
class Food2(object):
    """
    Food category
    Attribute: product name, discount, unit price, copies
    """
    def __init__(self,name,discount,price,servings):
        self.name = name
        self.discount = discount
        self.price = price
        self.servings = servings

class Customers(object):
    """
    Customer class
    Attribute: name, address, mobile number
    """
    def __init__(self,name,adress,mobile):
        self.name = name
        self.adress =  adress
        self.mobile = mobile

    #How to order food
    def order_food(self,fname,servings,fprice,discount):
        return Food2(fname,servings,fprice,discount)

    #Method of calculating total customer cost
    def cacl_all(self,flist):     #flist is the customer order
        money = 0
        for dd in flist:
            money += dd.price*dd.servings*dd.discount
        return money

if __name__ == '__main__':
    #Customer 1
    name = input("Welcome Junying Dumpling restaurant! Hello, your name:")
    mobile = input("May I have your mobile number")
    adress = input("May I have your address")

    c1 = Customers(name,mobile,adress)

    flist = []
    while True:
        fname = input("What do you need")
        servings = int(input("How many copies do you have"))
        price = eval(input("Price:"))
        discount = eval(input("Discount?"))

        flist.append(c1.order_food(fname,servings,price,discount))  #Add order

        answer = input("Do you need any more? ( y/n)")
        if answer != 'y' and answer != 'Y':
            break
    print("Thank you for your patronage!")
    print("What is your total cost%f"%(c1.cacl_all(flist))) #Call the method to calculate the total amount

Tags: Python AI

Posted on Fri, 26 Nov 2021 11:00:22 -0500 by toyartist