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
但它没有 运行。为什么?
代码中有几个错误:
- 缩进不正确
- 第二行是函数声明,应该以冒号结尾
:
代码还有其他几个问题:
Python 约定 class
名称以大写字母开头(所以 Station
,而不是 station
)
函数末尾的return完全多余
您确定要将 __station
方法设为私有吗? (参见此处:https://www.geeksforgeeks.org/private-methods-in-python/ and here: https://www.bogotobogo.com/python/python_private_attributes_methods.php 了解更多信息。)
为什么您的函数接受参数 d1
、d2
、a
和 b
?所有变量都在您的函数中定义。函数参数用于接受来自函数外部的输入
如果 self
不是 Station.station
的参数,一些 linter 会抱怨
考虑到以上所有内容,这是您的代码的更正版本:
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()
我应该介绍一下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
但它没有 运行。为什么?
代码中有几个错误:
- 缩进不正确
- 第二行是函数声明,应该以冒号结尾
:
代码还有其他几个问题:
Python 约定
class
名称以大写字母开头(所以Station
,而不是station
)函数末尾的return完全多余
您确定要将
__station
方法设为私有吗? (参见此处:https://www.geeksforgeeks.org/private-methods-in-python/ and here: https://www.bogotobogo.com/python/python_private_attributes_methods.php 了解更多信息。)为什么您的函数接受参数
d1
、d2
、a
和b
?所有变量都在您的函数中定义。函数参数用于接受来自函数外部的输入如果
self
不是Station.station
的参数,一些 linter 会抱怨
考虑到以上所有内容,这是您的代码的更正版本:
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()