目录

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程序设计》~

总结

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