I have found that when calling methods from within a method of a class I do not need to pass any variables to the method. Instead it simply inherits the attributes from that method when the method is called.
class Person(object):
def method1(self):
print(self.attr1)
def method2(self):
self.attr1 = 'attr1'
self.method1()
This works for me. However, my first intuitive attempt consisted of the following nonfunctional code.
class Person(object):
def method1(self, attr1):
print(self.attr1)
def method2(self):
self.method1('attr1')
Even though I figured out a solution to the problem, I'm very much interested to learn the underpinnings behind this one.
EDIT: The example I am trying to understand is this:
class Converter(object):
def split(self, x):
self.a, self.b, self.z, self.c = self.x.split(' ')
self.z = None
self.a = int(self.a)
def converter(self, unit, example):
self.x = ''
while self.x != 'exit':
self.x = input("Type '50 %s' or similar, or type 'units' to view valid units; type 'exit' to return to the main menu: " % (self.example))
if self.x == 'exit':
break
elif self.x == 'units':
print(list(self.units.keys()))
else:
self.split(self.x)
print(self.a / self.units[self.b] * self.units[self.c], self.c)
def volume(self):
self.units = { 'L': 1,
'mL': 1000,
'q': 1.05699,
'p': 2.11338,
'gal': 3.78541,
'oz': 33.814,
'ccm': 1000,
'cin': 61.024
}
self.example = 'L to q'
self.converter()
I don't understand why this wouldn't work:
class Converter(object):
def split(self, x):
self.a, self.b, self.z, self.c = self.x.split(' ')
self.z = None
self.a = int(self.a)
def converter(self):
self.x = ''
while self.x != 'exit':
self.x = input("Type '50 %s' or similar, or type 'units' to view valid units; type 'exit' to return to the main menu: " % (self.example))
if self.x == 'exit':
break
elif self.x == 'units':
print(list(self.units.keys()))
else:
self.split(self.x)
print(self.a / self.units[self.b] * self.units[self.c], self.c)
def volume(self):
self.units = { 'L': 1,
'mL': 1000,
'q': 1.05699,
'p': 2.11338,
'gal': 3.78541,
'oz': 33.814,
'ccm': 1000,
'cin': 61.024
}
self.converter({'L':2}, 'L to q')
EDIT2: Okay I think I understand now. The attributes are being attached to the instance object and I was simply not assigning the attributes that were passed onto the next function to the instance object.
self.attr1 = 'attr1', so the attribute is there. In the second example, you don't do that, so it isn't there.