Python中类的创建和实例化操作示例

作者:-牧野- 时间:2023-12-08 14:12:51 

本文实例讲述了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()

运行结果:

Name: cuiyongyuan, age: 10
Name: yuanli, age: 10

希望本文所述对大家Python程序设计有所帮助。

来源:https://blog.csdn.net/dcrmg/article/details/81231312

标签:Python,类,实例化
0
投稿

猜你喜欢

  • python pyg2plot的原理知识点总结

    2021-03-27 23:13:51
  • Python实现简单猜数字游戏

    2021-03-22 14:31:50
  • linux下mysql命令

    2011-01-04 19:42:00
  • Python 函数编编程的三大法宝map+filter+reduce分享

    2022-10-17 23:37:22
  • Python命令行参数定义及需要注意的地方

    2022-09-16 02:34:39
  • Python入门教程(十八)Python的For循环

    2021-07-30 04:09:59
  • VScode连接远程服务器上的jupyter notebook的实现

    2022-02-19 17:09:51
  • 用electron 打包发布集成vue2.0项目的操作过程

    2024-05-09 15:22:59
  • Go 语言的 :=的具体使用

    2024-05-10 13:58:56
  • PHP开发技巧之PHAR反序列化详解

    2023-11-15 02:23:45
  • keras回调函数的使用

    2022-08-22 11:42:41
  • VSCode如何巧用正则表达式快速处理字符段

    2022-06-13 06:44:00
  • Python算法中的时间复杂度问题

    2021-03-20 04:52:50
  • Django celery异步任务实现代码示例

    2021-12-10 21:38:40
  • 教你怎么用PyCharm为同一服务器配置多个python解释器

    2022-01-29 10:22:21
  • php统计数组不同元素的个数的实例方法

    2023-06-11 23:04:59
  • python之yield和Generator深入解析

    2022-09-16 01:25:39
  • Python操作Jira库常用方法解析

    2022-02-06 01:56:11
  • Python远程桌面协议RDPY安装使用介绍

    2023-11-06 05:37:23
  • python中文分词教程之前向最大正向匹配算法详解

    2023-07-23 12:51:22
  • asp之家 网络编程 m.aspxhome.com