python实例化对象的具体方法
作者:silencement 时间:2023-11-05 21:52:11
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()
实例扩展:
实例化过程:
class luffy_stu:
def __init__(self,name,age,sex):
self.name = name
self.age = age
self.sex = sex
def eat(self):
pass
if __name__=="__main__":
stu1 = luffy_stu('bao',21,'male')
#实例化过程:
#1. 是先产生一个stu1对象,
#2. luffy_stu.__init__('stu1','bao',21,'male')再将stu1对象传入__init__构造函数中实例化对象
来源:https://www.py.cn/faq/python/12328.html
标签:python,实例化对象
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
SQL SERVER数据库开发之asp存储过程应用
2008-05-19 12:55:00
![](https://img.aspxhome.com/file/UploadPic/up/2008051913142215.jpg)
Python微信企业号开发之回调模式接收微信端客户端发送消息及被动返回消息示例
2023-09-20 13:29:27
关于Go 是传值还是传引用?
2024-04-26 17:26:38
![](https://img.aspxhome.com/file/2023/9/134089_0s.png)
python判断windows系统是32位还是64位的方法
2023-08-08 15:17:04
JS模拟实现哈希表及应用详解
2024-04-23 09:25:52
![](https://img.aspxhome.com/file/2023/1/135531_0s.png)
C#使用Socket快速判断数据库连接是否正常的方法
2024-01-28 06:49:00
Oracle 数据表分区的策略
2023-07-08 12:19:18
垂直栅格与渐进式行距(下)
2009-07-09 16:52:00
Python+Pygame实现之走四棋儿游戏的实现
2023-08-29 21:34:55
![](https://img.aspxhome.com/file/2023/2/62312_0s.png)
FSO中的SubFolders 属性介绍
2008-01-05 13:57:00
.NET中开源文档操作组件DocX的介绍与使用
2024-06-05 09:28:18
YUI学习笔记(2)
2009-01-21 16:11:00
Python3 读取Word文件方式
2021-03-21 22:36:37
Python3爬虫学习之MySQL数据库存储爬取的信息详解
2024-01-19 23:06:19
![](https://img.aspxhome.com/file/2023/4/79634_0s.png)
如何用Axure制作Tab页签
2009-02-08 17:53:00
![](https://img.aspxhome.com/file/UploadPic/20092/8/1-19s.jpg)
PHP Laravel实现文件下载功能
2023-11-18 12:20:27
Go语言如何使用golang-jwt/jwt/v4进行JWT鉴权详解
2024-02-07 05:13:41
![](https://img.aspxhome.com/file/2023/7/105147_0s.jpg)
Mac PyCharm中的.gitignore 安装设置教程
2023-02-23 16:48:14
![](https://img.aspxhome.com/file/2023/2/67342_0s.jpg)
python实现TF-IDF算法解析
2021-06-02 03:27:51
![](https://img.aspxhome.com/file/2023/1/82961_0s.jpg)
MySQL索引最左匹配原则实例详解
2024-01-27 18:38:05
![](https://img.aspxhome.com/file/2023/5/71785_0s.png)