脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python中类的创建和实例化操作示例

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

2021-06-02 00:41-牧野- Python

这篇文章主要介绍了Python中类的创建和实例化操作,涉及Python面向对象程序设计中类的定义、实例化、方法调用等相关操作技巧,需要的朋友可以参考下

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

运行结果:

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

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

原文链接:https://blog.csdn.net/dcrmg/article/details/81231312

延伸 · 阅读

精彩推荐