python 类 计算两个值的和与差

python classes calculate sum and difference of two value

我应该介绍一下class的两个函数,并计算它们的差和和。

我写了这段代码:

class station: def __station(d1,d2,a,b) d1=int(input('temperature of first station: ')) d2=int(input('temperature of second station: ')) a=d1+d2 b=d2-d1 print('sum of temperature' ,a) print('difference of temperature',b) return

但它没有 运行。为什么?

代码中有几个错误:

  • 缩进不正确
  • 第二行是函数声明,应该以冒号结尾:

代码还有其他几个问题:

考虑到以上所有内容,这是您的代码的更正版本:

class Station:
    def station(self):
        d1=int(input('temperature of first station: '))
        d2=int(input('temperature of second station: '))
        a=d1+d2
        b=d2-d1
        print('sum of temperature', a)
        print('difference of temperature', b)

# demonstrate usage:

# instantiate Station
my_station = Station()

my_station.station()