Home>Article>Backend Development> How to create a class in python

How to create a class in python

藏色散人
藏色散人 Original
2019-06-28 11:12:54 6476browse

How to create a class in python

How to create a class in python?

In python, we also use the keyword class to create a class, with the class name first capital letters, with or without parentheses;

Instantiating a class in Python does not require the keyword new (there is no such keyword), and the instantiation of a class is similar to a function call;

# coding: utf-8 # 创建一个类,类名称第一个字母大写,可以带括号也可以不带括号 class Student(): student_count = 0 def __init__(self, name, salary): self.name = name self.age = salary Student.student_count += 1 def display_count(self): print('Total student {}'.format(Student.student_count)) def display_student(self): print('Name: {}, age: {}'.format(self.name,self.age)) def get_class(self): if self.age >= 7 and self.age < 8: return 1 if self.age >= 8 and self.age < 9: return 2 if self.age >= 9 and self.age < 10: return 3 if self.age >= 10 and self.age < 11: return 4 else: return 0 # 创建类的对象(实例化类) # 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()

Related recommendations: "Python Tutorial"

The above is the detailed content of How to create a class in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Can python do scripts? Next article:Can python do scripts?