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

yipeiwu_com5年前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()

运行结果:

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

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

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

相关文章

python实现对列表中的元素进行倒序打印

python实现对列表中的元素进行倒序打印

1.案例要求: """有列表["a", "d", "f", "j","z","Z","1"],对列表进行倒序,打印结果为["1","Z","z","j","f","d",""a]""...

在Pycharm中项目解释器与环境变量的设置方法

1.官网下载Pycharm community版如pycharm-community-2017.3.1.tar.gz。 2. #解压tar.gz tar xfz pycharm-*.ta...

关于pandas的离散化,面元划分详解

pd.cut pandas.cut(x, bins, right=True, labels=None, retbins=False, precision=3, include_low...

Python 多个图同时在不同窗口显示的实现方法

Python的matplotlib包可以轻松的将数据可视化,博主最近遇到了一个问题,博主想同时在两个窗口展示两张图,但是代码运行结果总是显示一张图,把当前的图删掉之后才能显示另一张图。网...

Python引用模块和查找模块路径

模块间相互独立相互引用是任何一种编程语言的基础能力。对于“模块”这个词在各种编程语言中或许是不同的,但我们可以简单认为一个程序文件是一个模块,文件里包含了类或者方法的定义。对于编译型的语...