Making the __init__ an abstract method:
from abc import ABCMeta, abstractmethod
class A(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, n):
self.n = n
if __name__ == '__main__':
a = A(3)
helps:
TypeError: Can't instantiate abstract class A with abstract methods __init__
Python 3 version:
from abc import ABCMeta, abstractmethod
class A(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self, n):
self.n = n
if __name__ == '__main__':
a = A(3)
Works as well:
TypeError: Can't instantiate abstract class A with abstract methods __init__
Answer from Mike Müller on Stack OverflowMaking the __init__ an abstract method:
from abc import ABCMeta, abstractmethod
class A(object):
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, n):
self.n = n
if __name__ == '__main__':
a = A(3)
helps:
TypeError: Can't instantiate abstract class A with abstract methods __init__
Python 3 version:
from abc import ABCMeta, abstractmethod
class A(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self, n):
self.n = n
if __name__ == '__main__':
a = A(3)
Works as well:
TypeError: Can't instantiate abstract class A with abstract methods __init__
A not so elegant solution can be this:
class A(object):
def __init__(self, n):
if self.__class__ == A:
raise Exception('I am abstract!')
self.n = n
Usage
class B(A):
pass
a = A(1) # Will throw exception
b = B(1) # Works fine as expected.
I thought I understood what abstract class means but my professor just commented that it wasn't a abstract class. What I did is essentially this:
first instruction: create an abstract base class with two int attributes then derived another class called Hero with a string attribute which stores the title "hero"
from abc import ABC
class Person(ABC):
def __init__(self, height, speed):
self.height = height
self.speed = speed
def walk(self):
//walk method
from person import Person
class Hero(Person):
def __init__(self, height, speed):
super().__init__(height, speed)
self.person_title = "Hero"
was this the right way to do it?
I have several different metric reports that share multiple things in common. As such, I have created an ABC that they all inherit. However, I would like all subclasses to automatically inherit the defined init in the ABC without having to copy the variables over and over in my inheriting classes.
Here is a sample of what I'm doing:
class Metric(metaclass=ABCMeta):
"""
Abstract class for all metrics to inherit from.
"""
def __init__(self, startdate=None, enddate=None):
self.startdate = startdate
self.enddate = enddate
@abstractclassmethod
def execute(self):
pass
class SampleReport(Metric):
def __init__(self):
super().__init__()
def execute(self):
passIn this scenario I won't be able to instantiate SampleReport and set startdate & enddate. I found a Stackoverflow thread describing the exact problem I'm facing, but I don't see a good solution to the issues: http://stackoverflow.com/questions/6535832/python-inherit-the-superclass-init