Shi23
Shi23

Reputation: 3

AttributeError when calling from subclass

When I call either method (get.__custnum, or get__mail) from the subclass I receive an attribute error saying the the object has no attribute named Subclass__attribute.

I checked that it wasn't just get_custnum that didn't work, still had the issue with get_mail.

My subclass, I have no issues with calling methods from the superclass.

class Customer(Person):

    def __init__(self, name, address, telnum, custnum, mail):
        Person.__init__(self, name, address, telnum)

        self.set_custnum = custnum
        self.set_mail = mail

    def set_custnum(self, custnum):
        self.__custnum = custnum

    def set_mail(self, mail):
        self.__mail = mail
        if mail == True:
            self.__mail = ('You have been added to the mailing list.')           

    def get_custnum(self):
        return self.__custnum

    def get_mail(self):
        return self.__mail

In my main function in a separate file.

from Ch11 import Ch11Ex3Classes

...

customer = Ch11Ex3Classes.Customer(name, address, telnum, custnum, mail)

...

print ('Customer Name: ', customer.get_name())
print ('Customer Address: ', customer.get_address())
print ('Customer telephone number: ', customer.get_telnum())
print ('Customer Number: ', customer.get_custnum())
print (customer.get_mail())

Error when main function is ran.

return self.__custnum
AttributeError: 'Customer' object has no attribute '_Customer__custnum'

The program should display the name, address, telephone number, customer number, and a message if they chose to join the mailing list. My output is the name, address, and telephone number (which are all from the superclass), but not the customer number, and mailing list message(which are from the subclass).

Upvotes: 0

Views: 101

Answers (2)

Alex Lucaci
Alex Lucaci

Reputation: 630

In your Customer init you may want to use super instead of using Person class explicitly. Also, in the same init you have used both self.set_custnum and self.set_mail as variables and you have defined it as a method. Try to use my edited Customer init.

class Customer(Person):

    def __init__(self, name, address, telnum, custnum, mail):
        super().__init__(self, name, address, telnum)

        self.set_custnum(custnum)
        self.set_mail(mail)

Upvotes: 1

Craig
Craig

Reputation: 4855

self.set_custnum = custnum isn't calling the method. You need to call the method in your __init__:

class Customer(Person):

    def __init__(self, name, address, telnum, custnum, mail):
        Person.__init__(self, name, address, telnum)

        self.set_custnum(custnum)
        self.set_mail(mail)

Upvotes: 0

Related Questions