I have two files in one folder, which are
"converters.py" is a module while "app.py" is a python file which tests it
here are the contents in the "converters.py module":
class KgLbs:
def __init__(self, weight):
self.weight = weight
def lbs_to_kg(self):
return self.weight * 0.45
def kg_to_lbs(self):
return self.weight / 0.45
and here are the ones in the "app.py" script:
from converters import KgLbs as kglbs
weight = int(input("Weight: "))
weight = kglbs.kg_to_lbs(weight)
print(weight)
and that's the error it gives me when I input an integer:
Weight: 52
Traceback (most recent call last):
File "app.py", line 4, in <module>
weight = kglbs.kg_to_lbs(weight)
File "C:\Users\Cyntexia\PycharmProject\Test\converters.py", line 8, in kg_to_lbs
return self.weight / 0.45
AttributeError: 'int' object has no attribute 'weight'
all i wanna do is input a simple integer, and then it will be converted to weight i desire altho this error comes in my goddamn way
With the way you designed your class, you have to use it in this way:
weight = KgLbs(weight).kg_to_lbs()
To use your way, you need to define your methods as @classmethods
and pass the weight
as an argument to them (no need for __init__
here):
class KgLbs:
@staticmethod
def lbs_to_kg(weight):
return weight * 0.45
@staticmethod
def kg_to_lbs(weight):
return weight / 0.45
weight = int(input("Weight: "))
weight = KgLbs.kg_to_lbs(weight)
print(weight)
You haven't initialised the weight for the object. It should've been like
from converters import KgLbs as kglbs
weight = int(input("Weight: "))
obj = kglbs(weight)
print(obj.kg_to_lbs())
Python is a strongly-typed language, and you are assigning a value of type int
to the weight
variable. Why do you think this int
value should behave like a KgLbs
?
use this instead:
from converters import KgLbs as kglbs
weight = kglbs(int(input("Weight: ")))
weight = weight.kg_to_lbs()
print(weight)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.