欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

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

时间:2022-02-02 09:34:22|栏目: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程序设计》~

总结

上一篇:Python图片检索之以图搜图

栏    目:Python代码

下一篇:详解python statistics模块及函数用法

本文标题:一篇文章带你了解Python中的类

本文地址:http://www.codeinn.net/misctech/192079.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有