Having trouble calling the parent class method from child class











up vote
0
down vote

favorite












I've started trying to learn Python after working with Java for the past year and decided to work on a couple class projects I've done and to write them in Python. I am getting an AttributeError at line 102, stating my super object has no attribute 'area'.



I've looked through different posts of how it's done, and I can't seem to figure out why this isn't working correctly for me after following other solutions.



It's a simple program that takes in input from the user, parses it, then depending on the shape type, will call the methods of the appropriate object type, then calculates and prints it out. For example, an input would be "R 3/4 5-7", supposed to weigh 8.37, or "P 1/4 5-6 2-3", supposed to weigh 126.07.



import math

class Shipment:
_weight = 0

def weight(self):
return self._weight

def frac_in_feet(self, frac):
thick_frac = frac.replace('/', "")
print("number is: ", thick_frac)
numerator = int(thick_frac[0])
denominator = int(thick_frac[1])
fraction_of_an_inch = numerator / denominator

return self.in_feet(0, fraction_of_an_inch)

def feet_and_inches_in_feet(self, feet_and_inches):
a = feet_and_inches.replace('-', "")
print("number is: ", a)
feet = int(a[0])
inches = int(a[1])

return self.in_feet(feet, inches)

def in_feet(self, feet, inches):
inches /= 12
print(feet + inches)
return feet + inches

def get_value_in_feet(self, str):
i = str.find('/')
j = str.find('-')

if i == -1:
value = self.feet_and_inches_in_feet(str)

if j == -1:
value = self.frac_in_feet(str)

return value

def add_item(self, quantity, description):
desc_values = description.replace(" ", "")
values =
shape_letter = desc_values[0]
i = 1
j = 4
for r in range(int(len(desc_values) / 3)):
print("r is: ", r)
values.append(self.get_value_in_feet(desc_values[i:j]))

i += 3
j += 3

if shape_letter == 'P':
if len(values) != 3:
raise ValueError("Plate needs three dimensions. ")

shape = Plate(values[0], values[1], values[2])

elif shape_letter == 'R':
if len(values) != 2:
raise ValueError("Rod needs two dimensions")

shape = Rod(values[0], values[1])

else:
raise ValueError("Shape letter ", shape_letter, " not recognized.")

self._weight += quantity * shape.weight()
return shape





class SteelShape:
_length = 0
_weight = 0

def length(self, length):
_length = length

def length(self):
return self._length

def weight(self, weight):
self._weight = weight

def weight(self):
return self._weight

class CalcShape(SteelShape):
_area = 0

def area(self, area):
self._area = area

def weight(self):
return self._area * self.length() * 489





class Rod(CalcShape):
def __init__(self, diameter, length):
radius = diameter / 2
super(CalcShape, self).area(math.pi * radius**2)
super(CalcShape, self).length





class Plate(CalcShape):
def __init__(self, thick, width, length):
super(CalcShape, self).area(thick * width)
super(SteelShape, self).length(length)

values =
shipment = Shipment()
shape = SteelShape()
line = input("Enter shape and dimensions: ")
shape = shipment.add_item(1, line)
if isinstance(shape, Plate):
print("Plate weighs ", shape.weight())

elif isinstance(shape, Rod):
print("Rod weighs ", shape.weight())


print("Total shipment weight: ", shipment.weight())
# R 3/4 5-7: supposed to weigh 8.37
# P 1/4 5-6 2-3: supposed to weigh 126.07









share|improve this question


















  • 2




    You don't call super(CalcShape, self).area(thick * width), you simply initialize the super class using super().__init__(*args) and then you can call self.area(thick * width).
    – SilverSlash
    Nov 5 at 3:02










  • stackoverflow.com/questions/607186/…
    – Carlos Mermingas
    Nov 5 at 3:05















up vote
0
down vote

favorite












I've started trying to learn Python after working with Java for the past year and decided to work on a couple class projects I've done and to write them in Python. I am getting an AttributeError at line 102, stating my super object has no attribute 'area'.



I've looked through different posts of how it's done, and I can't seem to figure out why this isn't working correctly for me after following other solutions.



It's a simple program that takes in input from the user, parses it, then depending on the shape type, will call the methods of the appropriate object type, then calculates and prints it out. For example, an input would be "R 3/4 5-7", supposed to weigh 8.37, or "P 1/4 5-6 2-3", supposed to weigh 126.07.



import math

class Shipment:
_weight = 0

def weight(self):
return self._weight

def frac_in_feet(self, frac):
thick_frac = frac.replace('/', "")
print("number is: ", thick_frac)
numerator = int(thick_frac[0])
denominator = int(thick_frac[1])
fraction_of_an_inch = numerator / denominator

return self.in_feet(0, fraction_of_an_inch)

def feet_and_inches_in_feet(self, feet_and_inches):
a = feet_and_inches.replace('-', "")
print("number is: ", a)
feet = int(a[0])
inches = int(a[1])

return self.in_feet(feet, inches)

def in_feet(self, feet, inches):
inches /= 12
print(feet + inches)
return feet + inches

def get_value_in_feet(self, str):
i = str.find('/')
j = str.find('-')

if i == -1:
value = self.feet_and_inches_in_feet(str)

if j == -1:
value = self.frac_in_feet(str)

return value

def add_item(self, quantity, description):
desc_values = description.replace(" ", "")
values =
shape_letter = desc_values[0]
i = 1
j = 4
for r in range(int(len(desc_values) / 3)):
print("r is: ", r)
values.append(self.get_value_in_feet(desc_values[i:j]))

i += 3
j += 3

if shape_letter == 'P':
if len(values) != 3:
raise ValueError("Plate needs three dimensions. ")

shape = Plate(values[0], values[1], values[2])

elif shape_letter == 'R':
if len(values) != 2:
raise ValueError("Rod needs two dimensions")

shape = Rod(values[0], values[1])

else:
raise ValueError("Shape letter ", shape_letter, " not recognized.")

self._weight += quantity * shape.weight()
return shape





class SteelShape:
_length = 0
_weight = 0

def length(self, length):
_length = length

def length(self):
return self._length

def weight(self, weight):
self._weight = weight

def weight(self):
return self._weight

class CalcShape(SteelShape):
_area = 0

def area(self, area):
self._area = area

def weight(self):
return self._area * self.length() * 489





class Rod(CalcShape):
def __init__(self, diameter, length):
radius = diameter / 2
super(CalcShape, self).area(math.pi * radius**2)
super(CalcShape, self).length





class Plate(CalcShape):
def __init__(self, thick, width, length):
super(CalcShape, self).area(thick * width)
super(SteelShape, self).length(length)

values =
shipment = Shipment()
shape = SteelShape()
line = input("Enter shape and dimensions: ")
shape = shipment.add_item(1, line)
if isinstance(shape, Plate):
print("Plate weighs ", shape.weight())

elif isinstance(shape, Rod):
print("Rod weighs ", shape.weight())


print("Total shipment weight: ", shipment.weight())
# R 3/4 5-7: supposed to weigh 8.37
# P 1/4 5-6 2-3: supposed to weigh 126.07









share|improve this question


















  • 2




    You don't call super(CalcShape, self).area(thick * width), you simply initialize the super class using super().__init__(*args) and then you can call self.area(thick * width).
    – SilverSlash
    Nov 5 at 3:02










  • stackoverflow.com/questions/607186/…
    – Carlos Mermingas
    Nov 5 at 3:05













up vote
0
down vote

favorite









up vote
0
down vote

favorite











I've started trying to learn Python after working with Java for the past year and decided to work on a couple class projects I've done and to write them in Python. I am getting an AttributeError at line 102, stating my super object has no attribute 'area'.



I've looked through different posts of how it's done, and I can't seem to figure out why this isn't working correctly for me after following other solutions.



It's a simple program that takes in input from the user, parses it, then depending on the shape type, will call the methods of the appropriate object type, then calculates and prints it out. For example, an input would be "R 3/4 5-7", supposed to weigh 8.37, or "P 1/4 5-6 2-3", supposed to weigh 126.07.



import math

class Shipment:
_weight = 0

def weight(self):
return self._weight

def frac_in_feet(self, frac):
thick_frac = frac.replace('/', "")
print("number is: ", thick_frac)
numerator = int(thick_frac[0])
denominator = int(thick_frac[1])
fraction_of_an_inch = numerator / denominator

return self.in_feet(0, fraction_of_an_inch)

def feet_and_inches_in_feet(self, feet_and_inches):
a = feet_and_inches.replace('-', "")
print("number is: ", a)
feet = int(a[0])
inches = int(a[1])

return self.in_feet(feet, inches)

def in_feet(self, feet, inches):
inches /= 12
print(feet + inches)
return feet + inches

def get_value_in_feet(self, str):
i = str.find('/')
j = str.find('-')

if i == -1:
value = self.feet_and_inches_in_feet(str)

if j == -1:
value = self.frac_in_feet(str)

return value

def add_item(self, quantity, description):
desc_values = description.replace(" ", "")
values =
shape_letter = desc_values[0]
i = 1
j = 4
for r in range(int(len(desc_values) / 3)):
print("r is: ", r)
values.append(self.get_value_in_feet(desc_values[i:j]))

i += 3
j += 3

if shape_letter == 'P':
if len(values) != 3:
raise ValueError("Plate needs three dimensions. ")

shape = Plate(values[0], values[1], values[2])

elif shape_letter == 'R':
if len(values) != 2:
raise ValueError("Rod needs two dimensions")

shape = Rod(values[0], values[1])

else:
raise ValueError("Shape letter ", shape_letter, " not recognized.")

self._weight += quantity * shape.weight()
return shape





class SteelShape:
_length = 0
_weight = 0

def length(self, length):
_length = length

def length(self):
return self._length

def weight(self, weight):
self._weight = weight

def weight(self):
return self._weight

class CalcShape(SteelShape):
_area = 0

def area(self, area):
self._area = area

def weight(self):
return self._area * self.length() * 489





class Rod(CalcShape):
def __init__(self, diameter, length):
radius = diameter / 2
super(CalcShape, self).area(math.pi * radius**2)
super(CalcShape, self).length





class Plate(CalcShape):
def __init__(self, thick, width, length):
super(CalcShape, self).area(thick * width)
super(SteelShape, self).length(length)

values =
shipment = Shipment()
shape = SteelShape()
line = input("Enter shape and dimensions: ")
shape = shipment.add_item(1, line)
if isinstance(shape, Plate):
print("Plate weighs ", shape.weight())

elif isinstance(shape, Rod):
print("Rod weighs ", shape.weight())


print("Total shipment weight: ", shipment.weight())
# R 3/4 5-7: supposed to weigh 8.37
# P 1/4 5-6 2-3: supposed to weigh 126.07









share|improve this question













I've started trying to learn Python after working with Java for the past year and decided to work on a couple class projects I've done and to write them in Python. I am getting an AttributeError at line 102, stating my super object has no attribute 'area'.



I've looked through different posts of how it's done, and I can't seem to figure out why this isn't working correctly for me after following other solutions.



It's a simple program that takes in input from the user, parses it, then depending on the shape type, will call the methods of the appropriate object type, then calculates and prints it out. For example, an input would be "R 3/4 5-7", supposed to weigh 8.37, or "P 1/4 5-6 2-3", supposed to weigh 126.07.



import math

class Shipment:
_weight = 0

def weight(self):
return self._weight

def frac_in_feet(self, frac):
thick_frac = frac.replace('/', "")
print("number is: ", thick_frac)
numerator = int(thick_frac[0])
denominator = int(thick_frac[1])
fraction_of_an_inch = numerator / denominator

return self.in_feet(0, fraction_of_an_inch)

def feet_and_inches_in_feet(self, feet_and_inches):
a = feet_and_inches.replace('-', "")
print("number is: ", a)
feet = int(a[0])
inches = int(a[1])

return self.in_feet(feet, inches)

def in_feet(self, feet, inches):
inches /= 12
print(feet + inches)
return feet + inches

def get_value_in_feet(self, str):
i = str.find('/')
j = str.find('-')

if i == -1:
value = self.feet_and_inches_in_feet(str)

if j == -1:
value = self.frac_in_feet(str)

return value

def add_item(self, quantity, description):
desc_values = description.replace(" ", "")
values =
shape_letter = desc_values[0]
i = 1
j = 4
for r in range(int(len(desc_values) / 3)):
print("r is: ", r)
values.append(self.get_value_in_feet(desc_values[i:j]))

i += 3
j += 3

if shape_letter == 'P':
if len(values) != 3:
raise ValueError("Plate needs three dimensions. ")

shape = Plate(values[0], values[1], values[2])

elif shape_letter == 'R':
if len(values) != 2:
raise ValueError("Rod needs two dimensions")

shape = Rod(values[0], values[1])

else:
raise ValueError("Shape letter ", shape_letter, " not recognized.")

self._weight += quantity * shape.weight()
return shape





class SteelShape:
_length = 0
_weight = 0

def length(self, length):
_length = length

def length(self):
return self._length

def weight(self, weight):
self._weight = weight

def weight(self):
return self._weight

class CalcShape(SteelShape):
_area = 0

def area(self, area):
self._area = area

def weight(self):
return self._area * self.length() * 489





class Rod(CalcShape):
def __init__(self, diameter, length):
radius = diameter / 2
super(CalcShape, self).area(math.pi * radius**2)
super(CalcShape, self).length





class Plate(CalcShape):
def __init__(self, thick, width, length):
super(CalcShape, self).area(thick * width)
super(SteelShape, self).length(length)

values =
shipment = Shipment()
shape = SteelShape()
line = input("Enter shape and dimensions: ")
shape = shipment.add_item(1, line)
if isinstance(shape, Plate):
print("Plate weighs ", shape.weight())

elif isinstance(shape, Rod):
print("Rod weighs ", shape.weight())


print("Total shipment weight: ", shipment.weight())
# R 3/4 5-7: supposed to weigh 8.37
# P 1/4 5-6 2-3: supposed to weigh 126.07






python class subclass






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 5 at 2:44









Mark Bussard

91




91








  • 2




    You don't call super(CalcShape, self).area(thick * width), you simply initialize the super class using super().__init__(*args) and then you can call self.area(thick * width).
    – SilverSlash
    Nov 5 at 3:02










  • stackoverflow.com/questions/607186/…
    – Carlos Mermingas
    Nov 5 at 3:05














  • 2




    You don't call super(CalcShape, self).area(thick * width), you simply initialize the super class using super().__init__(*args) and then you can call self.area(thick * width).
    – SilverSlash
    Nov 5 at 3:02










  • stackoverflow.com/questions/607186/…
    – Carlos Mermingas
    Nov 5 at 3:05








2




2




You don't call super(CalcShape, self).area(thick * width), you simply initialize the super class using super().__init__(*args) and then you can call self.area(thick * width).
– SilverSlash
Nov 5 at 3:02




You don't call super(CalcShape, self).area(thick * width), you simply initialize the super class using super().__init__(*args) and then you can call self.area(thick * width).
– SilverSlash
Nov 5 at 3:02












stackoverflow.com/questions/607186/…
– Carlos Mermingas
Nov 5 at 3:05




stackoverflow.com/questions/607186/…
– Carlos Mermingas
Nov 5 at 3:05












1 Answer
1






active

oldest

votes

















up vote
0
down vote













I think replacing the super and instead using staticmethod is a better choice. See here:



https://stackoverflow.com/a/735978/10416716



Hope this helps.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147660%2fhaving-trouble-calling-the-parent-class-method-from-child-class%23new-answer', 'question_page');
    }
    );

    Post as a guest
































    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    I think replacing the super and instead using staticmethod is a better choice. See here:



    https://stackoverflow.com/a/735978/10416716



    Hope this helps.






    share|improve this answer

























      up vote
      0
      down vote













      I think replacing the super and instead using staticmethod is a better choice. See here:



      https://stackoverflow.com/a/735978/10416716



      Hope this helps.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        I think replacing the super and instead using staticmethod is a better choice. See here:



        https://stackoverflow.com/a/735978/10416716



        Hope this helps.






        share|improve this answer












        I think replacing the super and instead using staticmethod is a better choice. See here:



        https://stackoverflow.com/a/735978/10416716



        Hope this helps.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 5 at 3:06









        Seraph Wedd

        1617




        1617






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53147660%2fhaving-trouble-calling-the-parent-class-method-from-child-class%23new-answer', 'question_page');
            }
            );

            Post as a guest




















































































            這個網誌中的熱門文章

            Tangent Lines Diagram Along Smooth Curve

            Yusuf al-Mu'taman ibn Hud

            Zucchini