标签:miss mis ssi 方法 ini class pos 空间 title
类中定义的函数是类的函数属性,类可以使用,但使用的就是一个普通的函数而已,意味着需要完全遵循函数的参数规则,该传几个值就传几个
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.name = 'tank'
stu1.age = 18
stu1.gender = 'male'
print(stu1.name, stu1.age, stu1.gender)
haoge 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)
zhuge 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)
haoge1 181 male1
init(stu2, 'sean1', 191, 'female1')
print(stu2.name, stu2.age, stu2.gender)
zhuge1 191 female1
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'}
标签:miss mis ssi 方法 ini class pos 空间 title
原文地址:https://www.cnblogs.com/nickchen121/p/10986649.html