2, class variables
Description : Reference variable assignment in a class by class or space
class User:
# 类变量(类空间定义的变量)
category = '未知类型'
# 类变量(通过类引用赋值的变量)
User.type = '普通用户'
1) call a class variable
(1) class by calling the class variables
Description : Gets and can change the value of the variable class by class
class User:
category = '未知类型'
print(User.category) # 通过类获取类变量
print('-'*30)
User.category = '改变后的类型' # 通过类更改类变量
print(User.category)
未知类型
------------------------------
改变后的类型
(2) the object by calling the class variables
Description : Gets the value can only be variable by the object class.
class User:
category = '未知类型'
u = User()
# 当对象本身没有 category 实例变量时,对象可以访问到该类变量
print(u.category)
未知类型
Note : The Object variable assignment for the new instance variables, not class variables.
class User:
category = '未知类型'
u = User()
u.category = '实例变量' # 通过对象对变量赋值为新增实例变量
print(u.category) # 当对象本身有 category 实例变量时,对象有限访问实例变量
print('-'*30)
print(User.category) # 类变量
2) Operation class variables
Description : Python class class variables may be added or deleted dynamically (dynamic Python's)
- In the class assignment is to increase body type variable is a new variable
- del delete class variables
class Item:
# 类变量
itemtype = '电子产品'
itemcolor = '未知'
print('种类:', Item.itemtype)
print('颜色:', Item.itemcolor)
print('-'*30)
Item.price = 100 # 增加新的类变量
print('价钱:', Item.price)
del Item.price # 删除类变量
种类: 电子产品
颜色: 未知
------------------------------
价钱: 100