1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| class Student: school = 'xx大学'
def __init__(self,name,sex,age): self.Name = name self.Sex = sex self.Age = age
def learn(self): print('%sis learning'%self.Name)
# 后产生对象 stu1 = Student('张三','男',11) stu2 = Student('李四','男',22) stu3 = Student('王五','男',33)
# 对象:特征和技能的结合体 # 类一系列对象相似的特征和相似的技能的结合体
# 类中的数据属性:是所有对象共有的 print(Student.school,id(Student.school)) print(stu1.school,id(stu1.school)) print(stu2.school,id(stu2.school)) print(stu3.school,id(stu3.school))
''' # 它们的id值都一样 xx大学 2644686064016 xx大学 2644686064016 xx大学 2644686064016 xx大学 2644686064016 '''
#---------------------------------------------------------- # 类中的函数属性:是绑定给对象使用的,绑定到不同的对象是不同的绑定方法,对象调用绑定方法时,把对象本身当作第一个参数传入也就是self print(Student.learn) print(stu1.learn) print(stu2.learn) print(stu3.learn)
''' # 它们的learn方法 地址都不一样 <function Student.learn at 0x00000271C5AFAEA0> <bound method Student.learn of <__main__.Student object at 0x00000271C5B045C0>> <bound method Student.learn of <__main__.Student object at 0x00000271C5B04710>> <bound method Student.learn of <__main__.Student object at 0x00000271C5B04748>> '''
# Student.learn() 报错 因为默认有个self参数 没有传递 learn() missing 1 required positional argument: 'self' Student.learn(123) # 继续报错 Student.learn(stu1) # 张三is learning Student.learn(stu2) # 李四is learning Student.learn(stu3) # 王五is learning
# 起始你可以这样调用 stu1.learn() # 张三is learning stu2.learn() # 李四is learning stu3.learn() # 王五is learning
|