Class is an abstract concept, such as human beings, birds, and fruits. It is a general term that is not specific to a certain object;
Object (object, refers to a specific instance, instance);
Add an instance variable to the object
# Add a skills instance variable
p.skills =['programming','writing']print(p.skills)
# Delete the name instance variable of the p object, instead of deleting the variable in the class, create a new object, the name instance variable is still the default constructor.
del p.name
# print(p.name)Will report an error
Python allows access to class variables through objects, but if the program tries to assign values to class variables through objects, the nature will change at this time. Python is a dynamic language, and assignment statements often mean defining new variables. Therefore, if the program assigns a value to a class variable through an object, it is not actually a "class variable assignment", but a new instance variable is defined. For example, the following program.
classInventory:
# Define two variables
quantity =2000
item ='mouse'
# Define instance method
def change(self,item,quantity):
self.item = item
self.quantity = quantity
# Create Inventory object
iv =Inventory()
iv.change('monitor',500)
# Access iv's item and quantity instance variables
print(iv.item) #monitor
print(iv.quantity) #500
# Access Inventotry's item and quantity class variables
print(Inventory.item) #mouse
print(Inventory.quantity) #2000
View extension:
Python's object orientation can be simply understood as the things you deal with are "objects". The variable refers to an object, the variable name is an object, and the related concept is the namespace. A class represents a class of things and is an object. The instance under the class is the specific manifestation of the class, which is equivalent to an individual with a certain characteristic, and these are all objects.
So far this article on how to understand python objects is introduced. For more related python objects how to understand content, please search the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support ZaLou.Cn more in the future!
Recommended Posts