POPON OOP - the object has no attribute

I am trying to learn how to program. I really want to learn how to program; I like its design and design. However, in Java and Python, I tried and failed with programs, since they relate to objects, classes, methods. I am trying to develop code for a program, but im stumped. I know this is a simple mistake. However, I am lost! I hope that someone can lead me to a work program, but also help me to study (criticism is not only expected, but also welcomed).

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..') 
+4
source share
3 answers

Classes and objects are tools for completing a task — they allow you to encapsulate data or state using a set of methods. However, your data is just a number. There is no need to encapsulate an integer, so there is no need to create a class.

In other words, do not create a class because, in your opinion, 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 not intended for any purpose, so the code is simpler and easier to read without them.

+4
source

1. Must be

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

cTOf has the same problem.

2.Variable numTo not defined

 numTo = convert.cTOf(numFrom) print (numTo) 
+1
source

You understand almost everything.

There is no self.numFrom because this is your parameter. Delete the lines numFrom =self.numFrom and everything will be fine.

0
source

Source: https://habr.com/ru/post/1439603/


All Articles