Python定制对象的独有特征
一、引入
class OldboyStudent:
school = "oldboy"
def choose_course(self):
print("is choosing course")
stu1 = OldboyStudent()
stu2 = OldboyStudent()
stu3 = OldboyStudent()
对于上述的学生类,如果类的属性改了,则其他对象的属性也会随之改变
ldboyStudent.school = "OLDBOY"
print(stu1.school)
OLDBOY
print(stu2.school)
OLDBOY
二、定制对象独有特征
print(stu1.__dict__)
{}
print(stu2.__dict__)
{}
对象本质类似于类,也是一个名称空间,但是对象的名称空间存放对象独有的名字,而类中存放的是对象们共有的名字。因此我们可以直接为对象单独定制名字。
stu1.name = "tank"
stu1.age = 18
stu1.gender = "male"
print(stu1.name, stu1.age, stu1.gender)
tank 18 male
try:
print(stu2.name, stu2.age, stu2.gender)
except Exception as e:
print(e)
"OldboyStudent" object has no attribute "name"
stu2.name = "sean"
stu2.age = 19
stu2.gender = "female"
print(stu2.name, stu2.age, stu2.gender)
sean 19 female
三、属性查找
首先从自身查找,没找到往类中找,类中没有则会报错。即对象的属性查找顺序为:自身–》类–》报错
四、类定义阶段定制属性
def init(obj, x, y, z):
obj.name = x
obj.age = y
obj.gender = z
init(stu1, "tank1", 181, "male1")
print(stu1.name, stu1.age, stu1.gender)
tank1 181 male1
init(stu2, "sean1", 191, "female1")
print(stu2.name, stu2.age, stu2.gender)
sean1 191 female1
使用上述方法虽然让我们定制属性更简单,但是还是太麻烦了,如果可以在实例化对象的时候自动触发定时属性,那就更方便了,因此可以使用类的__init__方法。
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)
#学习中遇到问题没人解答?小编创建了一个Python学习交流群:711312441
__init__() missing 3 required positional arguments: "name", "age", and "gender"
stu1 = OldboyStudent("nick", 18, "male")
**************************************************
通过上述现象可以发现,调用类时发生两件事:
创造一个空对象
自动触发类中__init__功能的执行,将stu1以及调用类括号内的参数一同传入
print(stu1.__dict__)
{"name": "nick", "age": 18, "gender": "male"}