class
In the United States, everyone drinks the same Coca Cola, whether it's the president or a tramp. Andy Warhol
Define a class
Definition: a class is the sum of abstract concepts of a series of behavioral transactions with common characteristics
# Small example: define a Coca Cola class and assign a formula variable class CocaCola: formula = ['caffine', 'sugar', 'water', 'soda']
You can see that there is a list variable formula in this class. The variable assigned in the class is the variable of the class, which is called the attribute of the class.
Class instantiation
coke_for_me = CocaCola() coke_for_you = CocaCola() print(CocaCola.formula) print(coke_for_me.formula) print(coke_for_you.formula)
['caffine', 'sugar', 'water', 'soda'] ['caffine', 'sugar', 'water', 'soda'] ['caffine', 'sugar', 'water', 'soda']
Giving a class a name is much like assigning a class to a variable. This behavior is called class instantiation, and the instantiated object becomes an instance or class instance.
Class attribute reference
print(CocaCola.formula) print(coke_for_me.formula) print(coke_for_you.formula)
['caffine', 'sugar', 'water', 'soda'] ['caffine', 'sugar', 'water', 'soda'] ['caffine', 'sugar', 'water', 'soda']
As shown above, enter. After the class name, and then enter the name of the class's attribute, which is the class attribute reference. It can also be found that all instances of the class share the properties of the class.
The properties of class are not different from normal variables, such as:
for element in coke_for_me.formula: print(element)
caffine sugar water soda
As can be seen from the above example, this attribute of the class is a list variable, which is the same as the normal list.
Instance properties
class CocaCola: formula = ['caffeine', 'sugar', 'water', 'soda'] coke_for_China = CocaCola() coke_for_China.local_logo = 'Coca Cola' # Create instance properties print(coke_for_China.local_logo) # Print instance property reference results
Coca Cola
local_ The logo attribute belongs to coke_ for_ The instance of China is unique to it. We call it instance attribute; At the same time, coke_ for_ The instance of China also has other properties of the CocaCola class.
Example method
Instances of classes can reference properties, and instances of classes can also use methods. Methods are functions, which we call methods here. Methods are used by instances of classes, so they are also called instance methods. (method is function)
class CocaCola: formula = ['caffeine', 'sugar', 'water', 'soda'] def drink(self): print('Energy') coke = CocaCola() coke.drink() # Call the drink function, whose function is to print 'Energy'
Energy
What is self used in the above example? Let's look at the following example
class CocaCola: formula = ['caffine', 'sugar', 'water', 'soda'] def drink(coke): print('Energy') coke = CocaCola() coke.drink()
Energy
It can be seen that the functions of the two pieces of code are the same and the output results are the same. It can be seen that the parameter self is the instance of the created class itself.
coke = CocaCola() coke.drink() == CocaCola.drink(coke) # The left and right sides are written exactly the same
Energy Energy True
The use method of the function is to put objects as parameters into the parentheses of the function. Once a class is instantiated, our use method is similar to that of using classes. Right: CocaCola uses the method (function / function) drink, which requires parameters. This parameter is the instance of coke itself, which is self. You can also write others, but you are used to writing self, so it is recommended to write self uniformly.
The instantiated object will be passed into the following method by the compiler as the first parameter.
More parameters
Like functions, class methods can also have their own parameters, such as trying to add a how to the. drink() method_ Much parameter:
class CocaCola(): formula = ['caffeine', 'sugar', 'water', 'soda'] def drink(self, how_much): if how_much == 'a sip': print('Cool~') elif how_much == 'whole bottle': print('Headache!') ice_coke = CocaCola() ice_coke.drink('a sip')
Cool~
"Magic method"
There are some methods in Python classes, which are called "magic methods"__ init__ () is one of them.
class CocaCola(): formula = ['caffeine', 'sugar', 'water', 'soda'] def __init__(self): self.local_logo = 'Coca Cola' def drink(self): print('Energy') coke = CocaCola() print(coke.local_logo)
Coca Cola
When the CocaCola() class is created, an instance property local is created_ Logo, and you can see that there is no reference when creating an instance__ init__ () method, but the subsequent contents are still executed automatically.
__ init__ () expansion and application of the method:
class CocaCola(): formula = ['caffeine','sugar','water','soda'] def __init__(self): for element in self.formula: print('Coke has {}!'.format(element)) def drink(self): print('Energy!') coke = CocaCola()
Coke has caffeine! Coke has sugar! Coke has water! Coke has soda!
In addition to the parameter self that must be written__ init__ () can also have its own parameters, and obj is also not required__ init__ () is also executed automatically. When instantiating, the parameters put after self in parentheses will be passed into the "magic method"__ init__ In (), the parameter usage of and function is exactly the same.
class CocaCola(): formula = ['caffeine', 'sugar', 'water', 'soda'] def __init__(self, logo_name): self.local_logo = logo_name def drink(self): print('Energy!') coke = CocaCola('Coca Cola') print(coke.local_logo)
Coca Cola
Class inheritance
# Define this class according to the latest Coca Cola formula class CocaCola: # When you do not inherit, you can write or not write the parenthesis, and the effect is the same calories = 140 sodium = 45 total_carb = 39 caffeine = 34 ingredients = [ 'High Fructose Corn Syrup', 'Carbonated Water', 'Phosphoric Acid', 'Natural Flavors', 'Caramel Color', 'Caffine' ] def __init__(self, logo_name): self.local_logo = logo_name def drink(self): print('You got {} cal energy!'.format(self.calories))
coke_a = CocaCola('Cocacola') print(coke_a.local_logo) coke_a.drink()
Cocacola You got 140 cal energy!
Due to different localization strategies and the development of new types, the packaging, volume and even formula of Coca Cola will change, but the only constant is that they have always been Coca Cola. All subclasses will inherit the Coca Cola brand. In python, the corresponding concept of class is called class inheritance
# Small example: no coffee cola class CaffeineFree(CocaCola): calories = 0 ingredients = [ 'High Fructose Corn Syrup', 'Carbonated Water', 'Phosphoric Acid', 'Natural Flavors', 'Caramel Color' ] def __init__(self, logo_name): self.local_logo = logo_name def drink(self): print('You got {} cal energy!'.format(self.calories))
coke_b = CaffeineFree('Cocacola-FREE') print(coke_b.local_logo) coke_b.drink()
Cocacola-FREE You got 0 cal energy!
It can be seen that writing cocacola in the brackets after CaffeineFree means that the subclass CaffeineFree inherits the parent class CocaCola, and the variables and methods in the parent class are completely inherited by the subclass. If there are special changes, they will also be overwritten.
Confusing class and instance properties
Q1: if the class attribute is re assigned, will it affect the reference of the class attribute? A1; meeting
class TestA: attr = 1 obj_a = TestA() TestA.attr = 42 print(obj_a.attr)
42
Q2: if the instance attribute is re assigned, will it affect the reference of class attribute? A1: No
class TestA: attr = 1 obj_a = TestA() obj_b = TestA() obj_a.attr = 42 print(obj_b.attr)
1
Q3: if the class attribute and instance attribute have the same name, what will be referenced later? A1: class attribute
class TestA: attr = 1 # Class properties def __init__(self): self.attr = 42 # Instance properties obj_a = TestA() print(obj_b.attr)
1
Explanation:
Extended understanding of classes
obj1 = 1 obj2 = 'String!' obj3 = [] obj4 = {} print(type(obj1), type(obj2), type(obj3), type(obj4))
<class 'int'> <class 'str'> <class 'list'> <class 'dict'>
Any kind of object in python is an instance of a class. These types are called built-in types, and they do not need to be instantiated.
from bs4 import BeautifulSoup soup = BeautifulSoup print(type(soup))
<class 'type'>
- The practice of class has no documentation and is not implemented for the time being. I can understand it.