如何允许对象将类方法作为属性?

时间:2017-10-28 14:23:35

标签: python oop inheritance

底部的解决方案

这是我的代码:

class Points:
    def __init__(self, a, b):
        self.a = a
        self.b = b 

    def gradient(self, coord):
        return (coord[0] - self.a) / (coord[1] - self.b)

class Attribute:
    def __init__(self, coordinate, c):
        self.coordinate = coordinate
        self.c = c

    def isEqual(self, coordinate2, c2):
        print self.coordinate.gradient(coordinate2)
        print self.c == c2

attributes = Attribute([2.345, 2.543], 1.123)
point = Points(3.45, 3.54)
attributes.isEqual(point, 5.0)

所以我有一个'Points'类,我存储一个坐标,(a,b),并定义一个方法'gradient',它以列表作为参数(另一个坐标),并计算渐变连接(a,b)和新坐标的线。

我还有一个'属性'类。在这个类中,我将另一个坐标定义为参数,以及其他一些数字。这个类有一个方法来检查在这个类中启动的坐标是否与isEqual参数中给出的其他坐标具有相同的坐标。

所以我在这里使用'Attribute'类定义'attributes'。然后我调用attributes.isEqual(point,5.0)来查找属性和point之间的渐变,并查看属性中的其他数字是否等于5.

这给了我以下输出:

MacBook-Air:Assignment1 Olly$ python try.py 
Traceback (most recent call last):
  File "try.py", line 39, in <module>
    attributes.isEqual(point, 5.0)
  File "try.py", line 33, in isEqual
    print self.coordinate.gradient(coordinate2)
AttributeError: 'list' object has no attribute 'gradient'

我不完全确定如何解决这个问题。我想也许我需要在创建Attribute类时继承Points类,以便使用Points类中的渐变方法。所以我尝试将Attribute类更改为以下内容:

class Attribute(Points):
    def __init__(self, coordinate, c, x, y):
        Points.__init__(self, x, y)
        self.coordinate = coordinate
        self.c = c

    def __str__(self):
        return "a and b (%s, %s); other number %s" % (self.coordinate[0], self.coordinate[1], self.c)

    def isEqual(self, coordinate2, c2):
        print self.coordinate.gradient(coordinate2)
        print self.c == c2

但这给了我一个不同的错误:

MacBook-Air:Assignment1 Olly$ python try.py 
Traceback (most recent call last):
  File "try.py", line 37, in <module>
    attributes = Attribute([2.345, 2.543], 1.123)
TypeError: __init__() takes exactly 5 arguments (3 given)

我真的不明白这个错误。

那么请你帮忙解决以下问题:

  1. 确定我在最初的情况下出错的地方。如果我是对的,我需要使用继承,请参阅2.
  2. 在我对继承的理解中找出我的错误。
  3. 谢谢。

    解决方案(接受Sweeper的回答)

    1. 上面的代码让Points类与list混淆。它们不一样,不能在它们之间进行隐式转换。渐变方法应该采用另一个Point而不是list

      def gradient(self, coord):
          return (coord.a - self.a) / (coord.b - self.b)
      
    2. 正在以错误的方式初始化属性。 __init__需要Point和一个数字,但上面的代码会给它一个list和一个数字。以下是正确的:

      attributes = Attribute(Point(2.345, 2.543), 1.123)
      

2 个答案:

答案 0 :(得分:2)

您的Point课程与list相混淆。它们根本不是 ,你不能在它们之间隐式转换。

你要解决的第一件事是渐变方法。它不应该列出一个清单。它应该采用另一个Point代替:

def gradient(self, coord):
    return (coord.a - self.a) / (coord.b - self.b)

其次,您是以错误的方式初始化Attribute__init__取一个坐标和一个数字,但是你给它一个列表和一个数字。

首先创建Point 然后创建Attribute

attributes = Attribute(Points(2.345, 2.543), 1.123)

我不明白为什么继承适合这里。

答案 1 :(得分:-1)

在顶部的原始代码中,self.coordinate是传递给Attribute构造函数的列表。我想你想做coordinate2.gradient(self.coordinate)因为coordinate2是作为参数传入的Pointself.coordinate是一个可索引的对象,这对Point::gradient的参数有意义。 1}}。