class Student: # 类的命名应该使用“驼峰体” # 1、变量的定义 stu_school=‘oldboy‘ # 数据 # 2、功能的定义 # 功能 def tell_stu_info(obj): print(‘学生信息:名字:%s 年龄:%s 性别:%s‘ %( obj[‘stu_name‘], obj[‘stu_age‘], obj[‘stu_gender‘] )) def set_info(obj,x,y,z): obj[‘stu_name‘]=x obj[‘stu_age‘]=y obj[‘stu_gender‘]=z # print(‘哈哈哈‘) # 类定义阶段就会执行 stu1=Student() # 每实例化一次Student类就得到一个学生对象 stu2=Student() stu3=Student()
class Student: # 1、变量的定义 stu_school=‘oldboy‘ #该方法会在对象产生之后自动执行,专门为对象进行初始化操作,可以有任意代码,但一定不能返回非None的值 def __init__(obj,x,y,z): obj.stu_name=x obj.stu_age=y obj.stu_gender=z # 实例化 stu1_obj=Student(‘egon‘,18,‘male‘) # Student.__init__(空对象,‘egon‘,18,‘male‘) stu2_obj=Student(‘lili‘,19,‘female‘) stu3_obj=Student(‘jack‘,20,‘male‘) # 调用类的过程又称之为实例化,发生了三件事 # 1、先产生一个空对象 # 2、python会自动调用类中的__init__方法然将空对象已经调用类时括号内传入的参数一同传给__init__方法 # 3、返回初始完的对象
class Student: # 1、变量的定义 stu_school=‘oldboy‘ count=0 # 空对象,‘egon‘,18,‘male‘ def __init__(self,x,y,z): Student.count += 1 self.stu_name=x # 空对象.stu_name=‘egon‘ self.stu_age=y # 空对象.stu_age=18 self.stu_gender=z # 空对象.stu_gender=‘male‘ # return None # 2、功能的定义 def tell_stu_info(self): print(‘学生信息:名字:%s 年龄:%s 性别:%s‘ %( self.stu_name, self.stu_age, self.stu_gender )) def set_info(self,x,y,z): self.stu_name=x self.stu_age=y self.stu_gender=z def choose(self,x): print(‘正在选课‘) self.course=x # 类中存放的是对象共有的数据与功能 Student.school # 访问数据属性,等同于Student.__dict__[‘school‘] Student.choose # 访问函数属性,等同于Student.__dict__[‘choose‘] # 但其实类中的东西是给对象用的 # 1、类的数据属性是共享给所有对象用的,大家访问的地址都一样 print(id(Student.stu_school)) print(id(stu1_obj.stu_school)) print(id(stu2_obj.stu_school)) print(id(stu3_obj.stu_school)) # 2、类中定义的函数主要是给对象使用的,而且是绑定给对象的,虽然所有对象指向的都是相同的功能,但是绑定到不同的对象就是不同的绑定方法,内存地址各不相同 # 类调用自己的函数属性必须严格按照函数的用法来 print(Student.tell_stu_info) print(Student.set_info) Student.tell_stu_info(stu1_obj) Student.tell_stu_info(stu2_obj) Student.tell_stu_info(stu3_obj)
原文:https://www.cnblogs.com/qjk95/p/12653695.html