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 Overflow[abc] Add abstract attributes via `abstract` type-hint - Ideas - Discussions on Python.org
abstract class, how to create it properly?
Enforcing __init__ signature when implementing it as an abstractmethod - Typing - Discussions on Python.org
Can I use __new__ for implementing an abstact base class?
Videos
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__
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?