To better explain the difference between class attributes and Object properties, first create the class people and two objects Student1 and Student2 as follows:
class people (object):
# class attributes are attributes that are defined inside a class and outside of the method
Money = 10000
def __init__ (self,name,age,gender=1):
# Object properties are properties defined within a method, such as in this example
# Name,age and gender are both object attributes
Self.name = Name
Self.age = Age
Self.gender = Gender
# Create objects of two classes
Student1 = People ("John", 20)
Student2 = People ("Dick", 25)
The difference between a class property and an object property:
# objects can invoke object properties and Class properties by object name. Property name
Print (Student2.name)
Print (Student2.money)
# and classes can invoke the properties of the class by using the class name. property name, but
# You can't call an object's properties this way
# For example, the class calls the Name property, and it reports an exception
# Attributeerror:type object ' People ' has no attribute ' name '
Print (People.money)
Print (People.name)
The results are as follows:
The difference between a class attribute and an object property in use:
# The three references are class attribute money before the operation.
# so these three property money's memory addresses are the same
Print (ID (student1.money))
Print (ID (student2.money))
Print (ID (people.money)
The results are as follows:
# Perform the following operations
Student1.money-= 1000
People.money-= 1000
# and print the memory address of the three
Print (ID (student1.money))
Print (ID (student2.money))
Print (ID (people.money))
Look at the results again:
You will find that the memory address of the money attribute referenced by Student1 is not the same as the other two, and the other two memory addresses are the same, for the following reasons:
The process of Student1.money-= 1000 is as follows: The first time you refer to the Money attribute, the process is as follows: You will first find out if there is money in the object, and if so, then go to the class to find out if there is a money attribute , if the money attribute is found in the class, then Student1 creates an object property money that calls its own object property at the second call, not the property in the class people, and student2 because it is not. So instead of creating your own money attribute, you refer to the properties of the class people, so student2 and people refer to the same property
# when Student2 performs the same operation, a Money attribute is also created in Student2
# at this time the money attribute of the three memory addresses are different.
Student2.money-= 1000
Print (ID (student1.money))
Print (ID (student2.money))
Print (ID (people.money))
The results are as follows: