目錄python
類中定義的函數是類的函數屬性,類能夠使用,但使用的就是一個普通的函數而已,意味着須要徹底遵循函數的參數規則,該傳幾個值就傳幾個函數
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)
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
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'}