Python的类 一篇文章带你了解Python中的类

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python的类 一篇文章带你了解Python中的类

NEUer_桓   2021-09-13 我要评论
想了解一篇文章带你了解Python中的类的相关内容吗,NEUer_桓在本文为您仔细讲解Python的类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,Python类,下面大家一起来学习吧。

1、类的定义

创建一个rectangle.py文件,并在该文件中定义一个Rectangle类。在该类中,__init__表示构造方法。其中,self参数是每一个类定义方法中的第一个参数(这里也可以是其它变量名,但是Python常用self这个变量名)。当创建一个对象的时候,每一个方法中的self参数都指向并引用这个对象,相当于一个指针。在该类中,构造方法表示该类有_width和_height两个属性(也称作实例变量),并对它们赋初值1。

__str__方法表示用字符串的方式表示这个对象,方便打印并显示出来,相当于Java中的类重写toString方法。其中,__init__和__str__是类提供的基本方法。

class Rectangle:
    # 构造方法
    def __init__(self, width=1, height=1):
        self._width = width
        self._height = height
    # 状态表示方法
    def __str__(self):
        return ("Width: " + str(self._width)
                + "\nHeight: " + str(self._height))
    # 赋值方法
    def setWidth(self, width):
        self._width = width
    def setHeight(self, height):
        self._height = height
    # 取值方法
    def getWidth(self):
        return self._width
    def getHeight(self):
        return self._height
    # 其它方法
    def area(self):
        return self._width * self._height

2、创建对象

新建一个Test.py文件,调用rectangle模块中的Rectangle的类。

import rectangle as rec
r = rec.Rectangle(4, 5)
print(r)
print()
r = rec.Rectangle()
print(r)
print()
r = rec.Rectangle(3)
print(r)

接着输出结果:

输出

打印Rectangle类的对象直接调用了其中的__str__方法。上图展示了初始化Rectangle对象时,构造方法中参数的三种不同方式。

创建一个对象有以下两种形式,其伪代码表示为:

1)objectName = ClassName(arg1,arg2,…)

2)objectName = moduleName.ClassName(arg1,arg2,…)

变量名objectName表示的变量指向该对象类型。

3、继承

如果往父类中增加属性,子类必须先包含刻画父类属性的初始化方法,然后增加子类的新属性。伪代码如下:

super().__ init __ (parentParameter1,…,parentParameterN)

新建一个square.py文件:

import rectangle as rec
class Square(rec.Rectangle):
    def __init__(self, square, width=1, height=1):
        super().__init__(width, height)
        self._square = square
    def __str__(self):
        return ("正方形边长为:" + str(self._width) +
                "\n面积为:" + str(self._square))
    def isSquare(self):
        if self._square == self.getWidth() * self.getWidth():
            return True
        else:
            return False
s = Square(1)
print(s)
print(s.isSquare())
s = Square(2)
print(s)
print(s.isSquare())

输出:

输出

以上内容参考自机械工业出版社《Python程序设计》~

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们