Python also uses the keyword class to create a class. The first letter of the class name is capitalized, with or without parentheses; the keyword new is not required to instantiate a class in Python (and there is no such keyword), and the instance of the class The similar function call method;
# coding:utf-8
# Create a class, the first letter of the class name is capitalized,Can be with or without parentheses
classStudent():
student_count=0def__init__(self,name,salary):
self.name=name
self.age=salary
Student.student_count+=1defdisplay_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
Create object of class (instantiate class)
There is no need to use the keyword new to instantiate a class in python (there is no such keyword), and the instantiation of a class is similar to a function call method.
student1=Student('cuiyongyuan',10)
student2=Student('yuanli',10)
student1.display_student()
student2.display_student()
student1_class=student1.get_class()
student2_class=student2.get_class()
Example extension:
The instantiation process:
classluffy_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')
# Instantiation process:
#1. Is to first generate a stu1 object,
#2. luffy_stu.__init__('stu1','bao',21,'male')Then pass in the stu1 object__init__Instantiate objects in the constructor
The above is the detailed content of the specific methods of python instantiating objects. For more information about how python instantiates objects, please pay attention to other related articles on ZaLou.Cn!
Recommended Posts