python - Can't instantiate abstract class ... with abstract methods -


i'm working on kind of lib, , weird reason have error.

  • here code. of course @abc.abstractmethod have uncommented
  • here tests

sorry couldn't copy , paste it

i went on basis code below works

test.py

import abc import 6  @six.add_metaclass(abc.abcmeta) class base(object):      @abc.abstractmethod     def whatever(self,):         raise notimplementederror  class subclass(base):      def __init__(self,):          super(base, self).__init__()         self.whatever()      def whatever(self,):         print("whatever") 

in python shell

>>> test import * >>> s = subclass() whatever 

why roster module i'm having error

can't instantiate abstract class player abstract methods _base__json_builder, _base__xml_builder 

thanks in advance

your issue comes because have defined abstract methods in base abstract class __ (double underscore) prepended. causes python name mangling @ time of definition of classes.

the names of function change __json_builder _base__json_builder or __xml_builder _base__xml_builder . , name have implement/overwrite in subclass.

to show behavior in example -

>>> import abc >>> import 6 >>> @six.add_metaclass(abc.abcmeta) ... class base(object): ...     @abc.abstractmethod ...     def __whatever(self): ...             raise notimplementederror ... >>> class subclass(base): ...     def __init__(self): ...             super(base, self).__init__() ...             self.__whatever() ...     def __whatever(self): ...             print("whatever") ... >>> = subclass() traceback (most recent call last):   file "<stdin>", line 1, in <module> typeerror: can't instantiate abstract class subclass abstract methods _base__whatever 

when change implementation following, works

>>> class subclass(base): ...     def __init__(self): ...             super(base, self).__init__() ...             self._base__whatever() ...     def _base__whatever(self): ...             print("whatever") ... >>> = subclass() whatever 

but tedious , may want think if want define functions __ (double underscore) . can read more name mangling here .


Comments