Python中的类

2021/9/13 1:05:16

本文主要是介绍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中的类的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程