很多小伙伴想知道在python中怎么创建类?那么今天小编就通过这篇文章来给大家分享一个实现在python中创建类的方法,感兴趣的小伙伴一定要耐心阅读完这篇文章。

python怎么创建类?这篇文章一定要看

在python中,我们只要使用同一个关键字class创建一个类,类名的首字母是大写,可以带括号也可以不带;

python中实例化类是不需要使用关键字new(也没有这个关键字)的,类的实例化类似函数调用方式;

# 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()

以上就是小编给大家带来的在python中创建类的相关知识点了,希望大家通过阅读小编的文章之后能够有所收获!如果大家觉得小编的文章不错的话,可以多多分享给有需要的人

更多python相关文章请访问分类:python

【版权声明】本文图文出自大盘站@dapan.cc,转载请注明出处!