对象没有属性
我正在尝试学习如何编程。 我真的很想学习如何编程; 我喜欢它的建筑和设计方面。 然而,在Java和Python中,我尝试过程序,因为它们与对象,类,方法有关。我试图为程序开发一些代码,但是我很难过。 我知道这是一个简单的错误。 但是我迷路了! 我希望有人能指导我一个工作计划,但也帮助我学习(批评不仅是预期的,而且是赞美)。
class Converter:
def cTOf(self, numFrom):
numFrom = self.numFrom
numTo = (self.numFrom * (9/5)) + 32
print (str(numTo) + ' degrees Farenheit')
return numTo
def fTOc(self, numFrom):
numFrom = self.numFrom
numTo = ((numFrom - 32) * (5/9))
return numTo
convert = Converter()
numFrom = (float(input('Enter a number to convert.. ')))
unitFrom = input('What unit would you like to convert from.. ')
unitTo = input('What unit would you like to convert to.. ')
if unitFrom == ('celcius'):
convert.cTOf(numFrom)
print(numTo)
input('Please hit enter..')
if unitFrom == ('farenheit'):
convert.fTOc(numFrom)
print(numTo)
input('Please hit enter..')
类和对象是完成任务的工具 - 它们允许您使用一组方法来封装数据或状态。 但是,您的数据只是一个数字。 没有必要封装整数,所以不需要创建一个类。
换句话说,不要创建一个类,因为你认为你应该创建一个类,因为它使你的代码更简单。
import sys
def f_to_c(x):
return (x - 32) * (5/9)
def c_to_f(x):
return x * (9/5) + 32
num_from = float(input('Enter a number to convert: '))
unit_from = input('What units would you like to convert from? ')
unit_to = input('What units would you like to convert to? ')
if (unit_from, unit_to) == ('fahrenheit', 'celsius'):
num_to = f_to_c(num_from)
elif (unit_from, unit_to) == ('celsius', 'fahrenheit'):
num_to = c_to_f(num_from)
else:
print('unsupported units')
sys.exit(1)
print('{} degrees {} is {} degrees {}'
.format(num_from, unit_from, num_to, unit_to))
Enter a number to convert: 40 What units would you like to convert from? celsius What units would you like to convert to? fahrenheit 40.0 degrees celsius is 104.0 degrees fahrenheit
convert对象和Converter类不起任何作用,所以如果没有它们,代码更简单,更容易阅读。
应该是
def fTOc(self, numFrom):
self.numFrom = numFrom
cTOf方法也有同样的问题。
2.Variable numTo未定义
numTo = convert.cTOf(numFrom)
print (numTo)
你几乎是对的。
没有self.numFrom因为它是你的参数。 删除行numFrom =self.numFrom ,你会没事的。
