Python abstract base class usage instance analysis, python abstract instance analysis

Source: Internet
Author: User

Python abstract base class usage instance analysis, python abstract instance analysis

This example describes the usage of the python abstract base class. Share it with you for your reference. The details are as follows:

To define an abstract class, you must use the abc module. This module defines an element class (ABCMeata), and the decorator @ abstractmethod, @ abstractproperty
If you want to instantiate a subclass that inherits Foo, The subclass must implement all the abstract methods of Foo (same as java); otherwise, an error is returned for instantiation.
Abstract classes cannot be instantiated directly.

#! Coding = utf-8from abc import ABCMeta, abstractmethod, abstractpropertyclass Foo: _ metaclass _ = ABCMeta @ abstractmethod # Use class Foo (metaclass = ABCMeta) syntax def spam (self, a, B): pass @ abstractproperty def name (self): passclass Bar (Foo): def spam (self, a, B): print a, B def name (): passb = Bar () B. spam (1, 2)

Abstract base classes support registering existing classes to belong to this base class, using the register () method
Register a class with the abstract base class. For an instance in the registration Class, Class detection operations involving subsequent base classes such as (isinstance, issubclass) will return True. When registering a class with the abstract base class, it does not check whether the class implements any abstract methods or features. This registration process only affects the type check.

Class Crok (object): def spam (self, a, c): print "gork. span" Foo. register (Grok)

I hope this article will help you with Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.