一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python面向对象之入门类和对象代码示例

时间:2021-12-16 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python面向对象之入门类和对象代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

什么是面向对象编程?

我们是不是听过面向过程,拿来放在一起对比就比较好理解了。

简单来理解,面向过程就是一切用函数解决一切文件,简单粗暴!

面向对象是面向过程编程之后才出现了,没有面向对象编程很多程序还不是照样开发。

面向对象,也使用函数,但是多了一个网,这个网把一个或者多个函数,和数据关联在一起,然后称为一类事物,也就是程序中的‘类'(class)

定义类,从具体代码来感受吧!

面向对象编程,首先提出的第一个概念就是‘class',类:

#这就是一个class的定义代码:
class hello_class():
    pass

然后通过class_name()这样调用来生产对象。

代码稍微升级一下,我们看看:

class hello_class():
    pass
#输出类信息
print(hello_class)
print(type(hello_class))
#创建类的实例对象
print(hello_class())
print(type(hello_class()))

稍微补充一下:

print函数输出类对象的结果:通常是<'class全名‘ object at id序列号>

下面是运行结果:

这里我们加入新知识点:类实例对象 , 通常直接说,实例。

实例是class产生的对象,所有某个hello_class对象的类型(通过type函数获取)都必定是hello_class。

多个类和对象的观察

看完一个类,我们再看看两个类的对比,结果也是一致的。

下面是两个类的定义和生成对象的代码展示:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/15 11:58 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
class student(object):
    “”“学委补充一下:__init___ 函数为类的初始化函数,在创建类对象实例的时候这个函数会被调用。”“”
    def __init__(self):
        print("hello, I am student")
class programmer(object):
    def __init__(self):
        print("hello, I am programmer")
class student(object):
    def __init__(self):
        print("hello, I am student")
class programmer(object):
    def __init__(self):
        print("hello, I am programmer")
s1 = student
print(s1)
p1 = programmer
print(p1)
s11 = student
print(s11)
p11 = programmer
print(p11)
print("*" * 16)
# 创建对象
s2 = student()
print(s2)
p2 = programmer()
print(p2)
# 创建对象
s3 = student()
print(s3)
p3 = programmer()
print(p3)

稍微解释一下:

s1 和 p1 这两个变量打印输出结果是‘class'类型的。

s11 和 p11 这两个变量打印输出结果是‘class'类型的,但是s1跟s11,p1跟p11 是不变的。

s2 和 p2 这两个变量打印输出结果是'object'类型的。

s3 和 p3 这两个变量打印输出结果是'object'类型的。

下面是运行结果:

初始化函数被调用了打印了对象信息。

到这里,大家应该都能知道class和object区别了吧

类: 描述了函数和属性的固定关系

(类实例)对象: 基于这种固定关系的一个活生生的个体,它的id是变化的。

热门栏目