object has no attribute

I am attempting to learn how to program. I really do want to learn how to program; I love the building and design aspect of it. However, in Java and Python, I have tried and failed with programs as they pertain to objects, classes, methods.. I am trying to develop some code for a program, but im stumped. I know this is a simple error. However I am lost! I am hoping someone can guide me to a working program, but also help me learn (criticism is not only expected, but APPRECIATED).

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..')

Classes and objects are tools to accomplish a task -- they allow you to encapsulate data or state with a set of methods. However, your data is just a number. There is no need to encapsulate the integer, so there is no need to create a class.

In other words, don't create a class because you think you should, create a class because it makes your code simpler.

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

The convert object and Converter class don't serve any purpose, so the code is simpler and easier to read without them.


1.It should be

def fTOc(self, numFrom):
    self.numFrom = numFrom

cTOf method has the same problem.

2.Variable numTo not defined

numTo = convert.cTOf(numFrom)
print (numTo)

You almost got it right.

There is no self.numFrom because it is your parameter. Remove the lines numFrom =self.numFrom and you will be fine.

链接地址: http://www.djcxy.com/p/55152.html

上一篇: 决定在Django中使用@staticmethod,@property或manager

下一篇: 对象没有属性