python怎么创建类


本文摘自php中文网,作者藏色散人,侵删。

python 怎么创建类?

python中同样使用关键字class创建一个类,类名称第一个字母大写,可以带括号也可以不带括号;

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

# 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 对目录下的文件进行过滤删除实例详解

linux如何安装Python

Python中日期和时间格式化输出的方法小结_Python

Python 文件操作详解

Python单引号和双引号的区别

Python是c语言开发的吗

Python怎么输入多行

Python函数之divmod数字处理函数

Python用户验证怎么弄

Python中set不常用吗

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...