0

I am new to python and created the below code to undersstand some conocepts of inheritance. however, the method print(x.showBaseListContents()) should display only the contents of the list but as shown below in the output i received NONE. please let me know when i received NONE

derived class

#from BaseClass import BaseClass
from BaseClass import BaseClass

class DerivedClass(BaseClass):

    def __init__(self, val1,val2, val3):
        BaseClass.__init__(self, val1,val2,val3)
        self.__baseList = []
        self.__val1 = val1
        self.__val2 = val2
        self.__val3 = val3

x = DerivedClass(10,20,30)
x.addValuesToBaseList()
s = x.getBaseListLength()
print(s)
print(x.showBaseListContents())

Baseclass

class BaseClass:        

    baseClassAttribute = 10

    def __init__(self, val1,val2, val3):
        self.__baseList = []
        self.__val1 = val1
        self.__val2 = val2
        self.__val3 = val3

    def getVal1(self):
        return self.__val1
    
    def getVal2(self):
        return self.__val2

    def getVal3(self):
        return self.__val3

    def addValuesToBaseList(self):
        self.__baseList.append(self.__val1)
        self.__baseList.append(self.__val2)
        self.__baseList.append(self.__val3)

    def getBaseListLength(self) :
        return len(self.__baseList)

    def showBaseListContents(self):
        for i in self.__baseList:
            print(i)

output

3
10
20
30
None
Amrmsmb
  • 1
  • 27
  • 104
  • 226
  • Note that leading-double-underscore names such as ``__val2`` trigger name-mangling, which prevents direct access from anything but the class itself. This is closely equivalent to ``private`` in ``private``/``protected``/``public`` schemes and usually *not* what you want. For example, the ``self.__val1 = val1`` etc. in ``DerivedClass.__init__`` are completely pointless because they create duplicate attributes that no code actually accesses. – MisterMiyagi Feb 19 '21 at 08:12

1 Answers1

0

It is because you have not returned anything from the method showBaseListContents() and the value returned by default is None.

 out = x.showBaseListContents() # out will get None
 print(out)

For the above code block, we will get the output printed as None as showBaseListContents() doesn't return anything.

Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
  • yes it does notreturn anything but it prints the values?!can it return void to avoid such error?? – Amrmsmb Feb 19 '21 at 08:24
  • 1
    there is no such thing as `return void` in Python. You could return `None` but that is analogous to `NULL` in `C/C++`. Ideally, if you don't return anything, just don't grab the return value. So, for your case, you need to simply do `x.showBaseListContents()` instead of `print(x.showBaseListContents())`. – Krishna Chaurasia Feb 19 '21 at 08:27