为什么要在python中使用类? [英] Why should I use classes in python?

查看:353
本文介绍了为什么要在python中使用类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个非常业余的Python学习者,最近我开始学习类的概念.我可以大致理解类的概念,但是我不明白为什么我不能简单地编写一些函数而不是编写类?

I am a very amateur learner of Python, and I have recently started learning the concept of classes. I can understand the concept of classes (very) roughly, but I can't understand why I can't simply write some functions instead of writing a class?

例如,(我正在从交互式python 中学习)给出的一项练习(我应该这样做)使用类编写)是:

For example, (I am learning from Interactive python) one of the exercise given (which I am supposed to write using a class) is :

  1. 添加一个distanceFromPoint方法,该方法的作用与distanceFromOrigin相似,不同之处在于它使用Point作为参数并计算该点与自身之间的距离.

  1. Add a distanceFromPoint method that works similar to distanceFromOrigin except that it takes a Point as a parameter and computes the distance between that point and self.

Point添加方法reflect_x,该方法将返回新的Point,这是点围绕x轴的反射.例如,Point(3, 5).reflect_x()(3, -5).

Add a method reflect_x to Point which returns a new Point, one which is the reflection of the point about the x-axis. For example, Point(3, 5).reflect_x() is (3, -5).

他们使用这样的类编写代码:

They written the code using classes like this:

import math

class Point:
    """ Point class for representing and manipulating x,y coordinates. """

def __init__(self, initX, initY):
    """ Create a new point at the given coordinates. """
    self.x = initX
    self.y = initY

def getX(self):
    return self.x

def getY(self):
    return self.y

def distanceFromOrigin(self):
    return ((self.x ** 2) + (self.y ** 2)) ** 0.5

def distanceFromPoint(self, otherP):
    dx = (otherP.getX() - self.x)
    dy = (otherP.getY() - self.y)
    return math.sqrt(dy**2 + dx**2)

p = Point(3, 3)
q = Point(6, 7)

print(p.distanceFromPoint(q))

当我可以像这样简单地编写它们时,为什么要使用类:

Why should I use class when I can write them simply like this:

def distanceFromPoint(p,q): # they are tuples
    y = (p[0]-q[0])**(2)+(p[1]-q[1])**(2)
    return y**(1/2)

def reflectx(p):
    return (p[0],-p[1])

p = (3,3)
q = (6,7)

推荐答案

使用OOP的一大优势是可扩展性.

One of the big advantages of using OOP is extensibility.

比方说,您编写了一个应用程序,该应用程序以点的形式处理大量数据.现在,您的客户将规格添加到每个点的x和y坐标上,您的应用程序需要知道每个点是什么颜色.

Let's say you'd written an application that processes lots of data in the form of points. Now your customer adds to the specification that as well as the x and y coordinate of each point, your app needs to know what colour each point is.

如果您编写了将每个点存储为元组(x, y)的代码,则可以将颜色添加为第三个值:(x, y, colour).但是现在您必须遍历所有代码,以查找由于更改了数据格式而损坏的地方.如果您使用过一个类,则可以简单地定义一个继承自Point的新类并添加必要的功能:

If you'd written your code to store each point as a tuple, (x, y), you might add the colour as a third value: (x, y, colour). But now you have to go through all of your code to find the places where it's broken because you changed the data format. If you'd used a class, you could simply define a new class that inherits from Point and adds the necessary capabilities:

class ColouredPoint(Point):
    """ Class for points which are coloured, based on Point """

    def __init__(self, initX, initY, initCol):
        Point.__init__(self, initX, initY)
        self.colour = initCol

p = ColouredPoint(3, 3, "green")
q = ColouredPoint(6, 7, "red")
r = Point(8, 4)

print(p.distanceFromPoint(q))
print(p.colour)
print(p.distanceFromPoint(r))

所有与Point类一起使用的代码仍将与新类一起使用,即使您没有编写或无法更改Point类的定义,也可以执行此操作.

All your code that worked with the Point class will still work with the new class, and you can do this even if you didn't write, or can't change, the definition of the Point class.

这篇关于为什么要在python中使用类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆