class
class inherit from object
class MyClass(object):
# class code follows...
Python 2, many reasons.
Python 3, no reason.
The following 2 classes are complete the same.
class ClassicSpam:
pass
class NewSpam(object):
pass
ABC, Abstract Base Classes
http://www.thedigitalcatonline.com/blog/2016/04/03/abstract-base-classes-in-python/
[1] to resolve: no-type-checking in python
try:
someobj[1]
except TypeError:
# when object is not subscriptable
[2] define sync interface among parent and child class.
Define it
by real inheritance
class ChildClass(ParentClass):
pass
by virtual subclass
ParentClass.register(ChildClass)
Registering a class does not imply any form of check about methods or attributes. Registering is just the promise that a given behaviour is provided by the registered class.
Create ABC
from abc import ABCMeta
class MyABC(metaclass=ABCMeta):
pass
MyABC.register(tuple)
assert issubclass(tuple, MyABC)
assert isinstance((), MyABC)
Metaclass
# Metaclass definition
class NewType(type):
def __init__(self, name, bases, namespace):
self.answer = 42
# Link class and metaclass
class Child(metaclass=NewType): pass
# Use the class
assert Child.answer == 42
metaclass = mixin
standard case:
class GrandParent(): pass
class Parent(GrandParent): pass
class Child(Parent): pass
c = Child()
calling get_name()
on c
, and it will check Child -> Parent -> GrandParent -> object
metaclass case:
class NewType(type): pass
class GrandParent(): pass
class Parent(GrandParent): pass
class Child(Parent, metaclass=NewType): pass
c = Child()
calling get_name()
on c
, and it will check Child -> Parent -> GrandParent -> object -> NewType
>>> Child.mro()
[<class '__main__.Child'>, <class '__main__.Parent'>, <class '__main__.GrandParent'>, <class 'object'>]
>>> Child.__class__
<class '__main__.NewType'>
>>>
abstractmethod = class with interface
class MyABC(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get(self):
pass
>>> m = MyABC()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class MyABC with abstract methods get
class Concrete(MyABC):
def get(self):
return 1
>>> c = Concrete()
>>>
prevents the class from being instantiated if the method is not implemented
Last updated
Was this helpful?