Python中类的创建和实例化操作示例
本文实例讲述了Python中类的创建和实例化操作。分享给大家供大家参考,具体如下:
python中同样使用关键字class创建一个类,类名称第一个字母大写,可以带括号也可以不带括号;
python中实例化类不需要使用关键字new(也没有这个关键字),类的实例化类似函数调用方式;
#coding:utf-8
#创建一个类,类名称第一个字母大写,可以带括号也可以不带括号
classStudent():
student_count=0
def__init__(self,name,salary):
self.name=name
self.age=salary
Student.student_count+=1
defdisplay_count(self):
print('Totalstudent{}'.format(Student.student_count))
defdisplay_student(self):
print('Name:{},age:{}'.format(self.name,self.age))
defget_class(self):
ifself.age>=7andself.age<8:
return1
ifself.age>=8andself.age<9:
return2
ifself.age>=9andself.age<10:
return3
ifself.age>=10andself.age<11:
return4
else:
return0
#创建类的对象(实例化类)
#python中实例化类不需要使用关键字new(也没有这个关键字),类的实例化类似函数调用方式。
student1=Student('cuiyongyuan',10)
student2=Student('yuanli',10)
student1.display_student()
student2.display_student()
student1_class=student1.get_class()
student2_class=student2.get_class()
运行结果:
Name:cuiyongyuan,age:10
Name:yuanli,age:10
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短