Home > Software design >  does anyone know much about python class? and its objects is giving me errors when i input some data
does anyone know much about python class? and its objects is giving me errors when i input some data

Time:03-24

built a class i get this error when i run the code

if unit == 'F': self.number = (number - 32) * 5/9 UnboundLocalError: local variable 'number' referenced before assignment

CodePudding user response:

number variable need to be declare first at the beginning of to() function. A simple : " number; " in first line of your to() function will solve the problem.

CodePudding user response:

class Temp:
    """A class to help work with lengths in various units"""
    number = 0
    def __init__(self, number, unit='C'):
        # Convert and store Temp as self.temp
        if unit == 'C': self.temp = number
        elif unit == 'F': self.temp = (number - 32) * 5/9
        elif unit == 'K': self.temp = number   273.15
        # Unit not recognised
        else: raise Exception("Unit not recognised")
    
    def to(self, unit, dp=None):
        
        # Convert self.temp to unit
        if unit == 'C': number = (5/9 * self.temp )   32
        elif unit == 'C': number = self.temp - 273.15 
        
        else: raise Exception("Unit not recognised")
        if dp: number = round(number, dp)
        return f"{number}{unit}"
    
    def __str__(self):
        return f"Temp: {self.temp}C"
    
    def __add__(self, other):
        return Length(self.metres   other.metres)
  • Related