The difference between Python class attributes and object attributes

The difference between Python class attributes and object attributes

  1. Naming rules:
    1.1 Class attributes are created by classes, and the naming rule is class name. Attribute name
    1.2 Object attributes are created by objects, and the naming rule is object name. Attribute name
  2. Calling method:
    2.1 Class attributes are called by the class
    2.2 Object attributes are called by the object
  3. Calling rules: when there are object attributes, class attributes cannot be called
  4. You can dynamically add and delete object properties; after adding, the object properties will only take effect for the current object. After deleting, calling again will call the class properties
class Person(object):
    # 这里的属性实际上属于类属性(用类名来调用)
    name = "person"
    def __init__(self, name):
        pass
        #对象属性
        self.name = name

print(Person.name)
per = Person("tom")
#对象属性的优先级高于类属性
print(per.name)
#动态的给对象添加对象属性
per.age = 18#只针对于当前对象生效,对于类创建的其他对象没有作用
print(Person.name)
print(per.age)
per2 = Person("lilei")
#print(per2.age)  #没有age属性

#删除对象中的name属性,在调用会使用到同名的类属性
print(per2.name)
del per2.name
print(per2.name)

#注意:以后千万不要讲对象属性与类属性重名,因为对象属性会屏蔽掉类属性。但是当删除对象属性后,在使用又能使用类属性了。

Guess you like

Origin blog.csdn.net/zhuan_long/article/details/110313220