得到TypeError,我不知道为什么?

时间:2019-07-02 07:15:35

标签: python-3.x class oop methods

任务是查找给定阵列的标准偏差。使用类和方法。 由于我是类和对象的新手,所以我没有在代码中遇到什么问题。

输入:10 40 30 50 20

   class Mean:
       def __init__(self,X):
           self.mean=(sum(X))/len(X)
           #return self.mean
   class Deviation(Mean):
        def deviation(self,X):
           Mean.__init__(self,X)
           m=Mean(X)
           self.d=0
           for i in X:
               self.d = self.d + (i-m)**2
               return self.d
   class Standard_Deviation:
       def display(self,X):
           sd=pow((Deviation(X))/(len(X)),0.5)
           return(sd)

   X=list(map(int,input().rstrip().split()))
   t=Standard_Deviation()
   z=t.display(X)
   print(z)

预期结果是14.1,但出现TypeError。

Traceback (most recent call last):
  File "Solution.py", line 29, in <module>
    z=t.display(X)
  File "Solution.py", line 24, in display
    sd=pow((Deviation(X))/(len(X)),0.5)
TypeError: unsupported operand type(s) for /: 'Deviation' and 'int'

2 个答案:

答案 0 :(得分:0)

代码中的主要问题是设计问题:您可能应该阅读一些有关面向对象的编程的知识,以便了解对象的性质,用途以及使用方法他们。

下面是一个类StatsData的示例,该类将一组值作为输入,然后允许计算数据的经典统计特征值:

class StatsData:
    def __init__(self, values):
        self.values = values[:]
        self._mean = None
        self._dev = None
        self._std_dev = None

    @property
    def mean(self):
        if self._mean is None:
            self._mean = sum(self.values) / len(self.values)
        return self._mean

    @property
    def dev(self):
        if self._dev is None:
            self._dev = 0
            for value in self.values:
                self._dev += (value - self.mean)**2
        return self._dev

    @property
    def std_dev(self):
        if self._std_dev is None:
            self._std_dev = pow(self.dev / len(self.values), 0.5)
        return self._std_dev

    def __str__(self):
        return f'mean: {stats.mean}, deviation: {stats.dev}, standard deviation: {stats.std_dev: 0.2f}'


input_values = [int(elt) for elt in "10 40 30 50 20".split()]
stats = StatsData(input_values)
print(stats)

输出:

mean: 30.0, deviation: 1000.0, standard deviation:  14.14

答案 1 :(得分:0)

您的代码中有一些错误。确实,您构造/连接这些类的方法并不是OOP的最佳或正确方法。

@Reblochon Masque的出色答案为您提供了一种更成熟的OOP方法。我只是将您的代码略微修改为可运行的代码。因此,您可以比较差异并更新您的OOP体验:)

class Mean:
    def __init__(self,X):
        self.data = X
        self.mean = sum(X)/len(X)
        #return self.mean


class Deviation(Mean):
    def __init__(self, X):
        # Since class Deviation is inherit from Mean, and 
        # class Mean has its own properties and calculations 
        # in its `__init__()`, (namely self.data and self.mean)
        # In order to get those from Mean, the subclass Deviation
        # need to explictly call its mother's __init__ with super,
        # Read the doc here https://docs.python.org/3/library/functions.html#super
        super(Deviation, self).__init__(X) 
        # This line does the same thing with # super().__init__(X) 
        # but more explictly.

        self.dev = self.deviation()
        self.var = self.dev / len(self.data)

    def deviation(self):
        dev = [(i-self.mean)**2 for i in self.data]
        return sum(dev)

class Standard_Deviation:
    def display(self, X):
        d = Deviation(X)
        sd = pow(d.dev/len(X), 0.5)
        return sd

# X=list(map(int,input().rstrip().split()))
X = [10, 40, 30, 50, 20]
t = Standard_Deviation()
z = t.display(X)
print(z)