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.
abstract class, how to create it properly?
Python Abstract Method With It's own __init__ function - Stack Overflow
Adding @abstractmethod __init__ to ABC breaks staticmethods
__init__ in ABC abstract class in Python - Stack Overflow
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
Hello. In this first example, I have a short and straightforward code w/ a class for interface. It doesn't inherit from ABC and doesn't have any abstract methods.
class Abs():
def __init__(self, name, age):
self.name = name
self.age = age
def go_to(self):
return f"{self.name} is going to {self.place}."
class Teacher(Abs):
place = "work"
class Student(Abs):
place = "school"
t1 = Teacher("James", 56)
s1 = Student("Tim", 15)
print(t1.go_to())
print(s1.go_to())In this second example, it's the exact opposite.
from abc import ABC, abstractmethod
class Abs(ABC):
def __init__(self, name, age):
self.name = name
self.age = age
@abstractmethod
def go_to(self):
...
class Teacher(Abs):
place = "work"
def go_to(self):
return f"{self.name} is going to {self.place}."
class Student(Abs):
place = "school"
def go_to(self):
return f"{self.name} is going to {self.place}."
t1 = Teacher("James", 56)
s1 = Student("Tim", 15)
print(t1.go_to())
print(s1.go_to())Both examples have the same output. In the tutorials/articles I've read, most times the second example is preferred. In the abstract class, abstract methods get defined and decorated, and then in the inheriting classes they all get redefined with the rest of the logic. What's the point of creating a class w/ abstract methods which later on we redefine? What issue does that solve? Why not just proceed as in the first example - simple, less code, one parent class for the interface, if we need to add other details, we do so in the base class once and handle the extra logic with that additional info there. Doesn't the first code present a better example of loose coupling - just one connection between parent and child classes, where in the second code, we get connections between parent/child in every method that we redefine? I feel like I'm missing something, because to me, the second example is much more spaghetti-like. If anyone can explain why it's a good practice to redefine abstract methods that would be nice. Also, is it a bad practice to write code as in the first example, w/o ABC+@abstractmethod in the parent class?
Thanks.