文章目录
- 1、简介
- 2、示例
1、简介
python 类方法的 ,一般使用起来 是用来实现对类属性 的操作
2、示例
class person(): # 类
name = "lum" # 属性 姓名
age = 27 # 属性 年龄
def __init__(self): # 构造函数
self.sex = "man"
a = person() # 实例化对象
print (a.age)
print(a.__dict__) #打印对象的属性
a.age = 20 # 实例化对象赋值
print(a.age) # 打印 对象的 age
print(person.age) # 打印 类的 age
print(a.__dict__) # 查看 对象的 属性
print(person.__dict__) # 查看类的属性
打印
27
{‘sex’: ‘man’} # 刚开始 a 里面是没有实例化的 age 属性
20 # 示例对象
27 # 类 属性 没有改变
{‘sex’: ‘man’, ‘age’: 20} # 示例对象并没有 类属性的变量,age 是自己加上去的实例化变量
{‘module’: ‘main’, ‘name’: ‘lum’, ‘age’: 27, ‘init’: <function person.init at 0x000001B653131BF8>, ‘dict’: <attribute ‘dict’ of ‘person’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘person’ objects>, ‘doc’: None} # 类的属性并没有改变
我们添加 一个修改 属性的 函数
class person():
name = "lum"
age = 27
def __init__(self):
self.sex = "man"
def change(cls,ageValue):
cls.age = ageValue
a = person()
print (a.age)
print(a.__dict__)
a.change(20)
print(a.age)
print(person.age)
print(a.__dict__)
print(person.__dict__)
打印:
27
{‘sex’: ‘man’}
20
27
{‘sex’: ‘man’, ‘age’: 20} # 这和个时候 同样是 在实例中创建一个 age
{‘module’: ‘main’, ‘name’: ‘lum’, ‘age’: 27, ‘init’: <function person.init at 0x0000024D5C231BF8>, ‘change’: <function person.change at 0x0000024D5C231B70>, ‘dict’: <attribute ‘dict’ of ‘person’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘person’ objects>, ‘doc’: None}
依然没有 改变 类的属性值
这个时候我们加上 @classmethod 修饰符
class person():
name = "lum"
age = 27
def __init__(self):
self.sex = "man"
@classmethod
def change(cls,ageValue):
cls.age = ageValue
a = person()
print (a.age)
print(a.__dict__)
a.change(20)
print(a.age)
print(person.age)
print(a.__dict__)
print(person.__dict__)
27
{‘sex’: ‘man’}
20
20
{‘sex’: ‘man’} # 这个时候在示例中 没有创建 age ,是对类变量进行赋值
{‘module’: ‘main’, ‘name’: ‘lum’, ‘age’: 20, ‘init’: <function person.init at 0x0000021431B91BF8>, ‘change’: <classmethod object at 0x0000021431BC6198>, ‘dict’: <attribute ‘dict’ of ‘person’ objects>, ‘weakref’: <attribute ‘weakref’ of ‘person’ objects>, ‘doc’: None}