Python and Mixins with Super - python

I have the following class
from somewhere import ParentClass
from mixin_file import Mixin1 and Mixin2
class Test(Mixin1, Mixin2, ParentClass):
def __init__(self):
super(Test, self).__init__()
in mixin_file
from abc import ABCMeta, abstractmethod
class Mixin1(object):
__metaclass__ = ABCMeta
#abstractmethod
def do_something(self):
pass
class Mixin2(object):
def hello(self):
pass
and when I run
x = Test()
the error
TypeError:__init__() takes exactly 0 arguments (2 given)
Do I need to pass the Mixin whens I initialize 'x'? I'm not quite clear on this behavior.

Order of operations ended up being the issue here. I needed to add the mixins after so
class Test(Mixin1, Mixin2, ParentClass):
goes too
class Test(ParentClass, Mixin1, Mixin2):

Related

How to override static abstract method of base in a subclass?

I have an abstract class with a static function that calls other abstract functions. But when I'm creating a new class and overriding abstract function still the original (abstract) function is running.
I have written an example similar to my problem. Please help.
In the following example, I want to run do_something() from Main not Base.
from abc import ABC, abstractmethod
class Base(ABC):
#staticmethod
#abstractmethod
def do_something():
print('Base')
#staticmethod
def print_something():
Base.do_something()
class Main(Base):
#staticmethod
def do_something():
print('Main')
Main.print_something()
Output:
Base
Main.print_something doesn't exist, so it resolves to Base.print_something, which explicitly calls Base.do_something, not Main.do_something. You probably want print_something to be a class method instead.
class Base(ABC):
#staticmethod
#abstractmethod
def do_something():
print('Base')
#classmethod
def print_something(cls):
cls.do_something()
class Main(Base):
#staticmethod
def do_something():
print('Main')
Main.print_something()
Now when Main.print_something resolves to Base.print_something, it will still receive Main (not Base) as its argument, allowing it to invoke Main.do_something as desired.

TypeError: Can't instantiate abstract class <...> with abstract methods

Here is my code:
from abc import ABC
from abc import abstractmethod
class Mamifiero(ABC):
"""docstring for Mamifiero"""
def __init__(self):
self.alimentacion = 'carnivoro'
#abstractmethod
def __respirar(self):
print('inhalar... exhalar')
class Perro(Mamifiero):
"""docstring for Perro"""
def __init__(self, ojos=2,):
self.ojos = ojos
I want that perro.respirar() prints 'inhalar... exhalar' but when I want to instantiate a Perro class show me this error. I want to know what is wrong with my script
By definition (read the docs), an abstract call is a class which CANNOT be instantiated until it has any abstract methods not overridden. So as in the Object-Oriented Programming by design.
You have an abstract method Perro.__respirar() not overridden, as inherited from the parent class. Or, override it with a method Perro.__respirar(), and do something there (maybe even call the parent's method; but not in case it is private with double-underscore, of course).
If you want to instantiate Perro, just do not make that method abstract. Make it normal. Because it also has some implementation, which suggests it is a normal base-class'es method, not an abstract method.
You need to override __respirar() abstract method in Perro class as shown below:
from abc import ABC
from abc import abstractmethod
class Mamifiero(ABC):
"""docstring for Mamifiero"""
def __init__(self):
self.alimentacion = 'carnivoro'
#abstractmethod
def __respirar(self):
print('inhalar... exhalar')
class Perro(Mamifiero):
"""docstring for Perro"""
def __init__(self, ojos=2,):
self.ojos = ojos
# You need to override
def __respirar(self):
print('Hello')

Can't instantiate abstract class with abstract methods

I'm working on a kind of lib, and I'm getting an error.
Here is my code. Of course #abc.abstractmethod have to be uncommented
Here are my tests
Sorry couldn't just copy and paste it
I went on the basis that the code below works.
test.py:
import abc
import six
#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 the python shell:
>>> from test import *
>>> s = SubClass()
whatever
For my roster module, why am I getting this error:
Can't instantiate abstract class Player with abstract methods _Base__json_builder, _Base__xml_builder
Your issue comes because you have defined the abstract methods in your base abstract class with __ (double underscore) prepended. This causes python to do name mangling at the time of definition of the classes.
The names of the function change from __json_builder to _Base__json_builder or __xml_builder to _Base__xml_builder . And this is the name you have to implement/overwrite in your subclass.
To show this behavior in your example -
>>> import abc
>>> import six
>>> #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")
...
>>> a = SubClass()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class SubClass with abstract methods _Base__whatever
When I change the implementation to the following, it works
>>> class SubClass(Base):
... def __init__(self):
... super(Base, self).__init__()
... self._Base__whatever()
... def _Base__whatever(self):
... print("whatever")
...
>>> a = SubClass()
whatever
But this is very tedious , you may want to think about if you really want to define your functions with __ (double underscore) . You can read more about name mangling here .
I got the same error below:
TypeError: Can't instantiate abstract class Animal with abstract methods sound
When I tried to instantiate Animal abstract class as shown below:
from abc import ABC, abstractmethod
class Animal(ABC):
#abstractmethod
def sound(self):
print("Wow!!")
obj = Animal() # Here
obj.sound()
And also, I got the same error below:
TypeError: Can't instantiate abstract class Cat with abstract methods sound
When I didn't override sound() abstract method in Cat class, then I instantiated Cat class as shown below:
from abc import ABC, abstractmethod
class Animal(ABC):
#abstractmethod
def sound(self):
print("Wow!!")
class Cat(Animal):
pass # I didn't override "sound()" abstract method
obj = Cat() # Here
obj.sound()
So, I overrided sound() abstract method in Cat class, then I instantiated Cat class as shown below:
from abc import ABC, abstractmethod
class Animal(ABC):
#abstractmethod
def sound(self):
print("Wow!!")
# I overrided "sound()" abstract method
class Cat(Animal):
def sound(self):
print("Meow!!")
obj = Cat() # Here
obj.sound()
Then, I could solve the error:
Meow!!
Easiest way to make it behave like it did in Python 2 is to use
exec('print("your code")', globals())
This will allow your code to access imports, classes and functions defined in the code will work correctly, etc.
This should only be done w/ code you trust.

No error while instantiating abstract class, even though abstract method is not implemented

I was trying out the below python code:
from abc import ABCMeta, abstractmethod
class Bar:
__metaclass__ = ABCMeta
#abstractmethod
def foo(self):
pass
class Bar2(Bar):
def foo2(self):
print("Foo2")
b = Bar()
b2 = Bar2()
I thought having #abstractmethod will ensure that my parent class will be abstract and the child class would also be abstract as it is not implementing the abstract method. But here, I get no error trying to instantiate both the classes.
Can anyone explain why?
You must set meta-class of Bar class to ABCMeta.
Python 2:
class Bar:
__metaclass__ = ABCMeta
#abstractmethod
def foo(self):
pass
Python 3:
class Bar(object, metaclass=ABCMeta):
#abstractmethod
def foo(self):
pass

Subclassing a Python class to inherit attributes of super class

I'm trying to inherit attributes from a super class but they are not being initialized correctly:
class Thing(object):
def __init__(self):
self.attribute1 = "attribute1"
class OtherThing(Thing):
def __init__(self):
super(Thing, self).__init__()
print self.attribute1
This throws an error since attribute1 is not an attribute of OtherThing, even though Thing.attribute1 exists. I thought this was the correct way to inherit and extend a super class. Am I doing something wrong? I don't want to create an instance of Thing and use its attributes, I need it to inherit this for simplicity.
You have to give, as argument, the class name (where it is being called) to super():
super(OtherThing, self).__init__()
According to Python docs:
... super can be used to refer to parent classes without naming them
explicitly, thus making the code more maintainable.
so you are not supposed to give the parent class.
See this example from Python docs too:
class C(B):
def method(self, arg):
super(C, self).method(arg)
Python3 makes this easy:
#!/usr/local/cpython-3.3/bin/python
class Thing(object):
def __init__(self):
self.attribute1 = "attribute1"
class OtherThing(Thing):
def __init__(self):
#super(Thing, self).__init__()
super().__init__()
print(self.attribute1)
def main():
otherthing = OtherThing()
main()

Categories