第十一章、定制对象独有特征
一、引入
class OldboyStudent:
school = 'oldboy'
def choose_course(self):
print('is choosing course')
stu1 = OldboyStudent()
stu2 = OldboyStudent()
stu3 = OldboyStudent()
- 对于上述的学生类,如果类的属性改了,则其他对象的属性也会随之改变
OldboyStudent.school = 'OLDBOY'
print(stu1.school)
OLDBOY
print(stu2.school)
#OLDBOY
二、定制对象独有特征
print(stu1.__dict__)
{}
print(stu2.__dict__)
{}
- 对象本质类似于类,也是一个名称空间,但是对象的名称空间存放对象独有的名字,而类中存放的是对象们共有的名字。因此我们可以直接为对象单独定制名字。
stu1.country='China'
print(stu1.country)
#China
三、类定义阶段定制属性
class OldboyStudent:
school = 'oldboy'
def __init__(self, name, age, gender):
"""调用类的时候自动触发"""
self.name = name
self.age = age
self.gender = gender
print('*' * 50)
def choose_course(self):
print('is choosing course')
try:
stu1 = OldboyStudent()
except Exception as e:
print(e)
__init__() missing 3 required positional arguments: 'name', 'age', and 'gender'
接下来为对象赋值
stu1 = OldboyStudent('nick', 18, 'male')
print(stu1.__dict__)
#{'name': 'nick', 'age': 18, 'gender': 'male'}
通过上述现象可以发现,调用类时发生两件事:
创造一个空对象
自动触发类中__init__功能的执行,将stu1以及调用类括号内的参数一同传入