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()
实例扩展:
实例化过程:
class luffy_stu:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def eat(self):
pass
if __name__=="__main__":
stu1 = luffy_stu('bao',21,'male')
#实例化过程:
#1. 是先产生一个stu1对象,
#2. luffy_stu.__init__('stu1','bao',21,'male')再将stu1对象传入__init__构造函数中实例化对象
以上就是python实例化对象的具体方法的详细内容,更多关于python如何实例化对象的资料请关注ZaLou.Cn其它相关文章!