New Writing of the Python abstract class and the writing of the Python abstract class

Source: Internet
Author: User

New Writing of the Python abstract class and the writing of the Python abstract class

I remember in the previous book learn python, because there was no official support at the time, I could only use the hack method to implement the abstract method. The simplest method is as follows:

Class MyCls (): def foo (self): print ('method no implement ') running example >>> a = MyCls () >>>. foo () method no implement >>>

Although this method can be used, but the prompt is not obvious, it is still easy to misuse. Of course, there are better ways to make it more acceptable.

class MyCls():  def foo(self):    raise Exception('no implement exception', 'foo method need implement')

A simple use case

>>> a = MyCls()>>> a.foo()Traceback (most recent call last): File "<interactive input>", line 1, in <module> File "<clipboard>", line 3, in fooException: ('no implement exception', 'foo method need implement')

This is what we wrote before 2.7. 2.7 gave us a new support method! Abc module (abstruct base class), which has been implemented in py3k, is a back port.

Let's take a look at the new writing method.

from abc import ABCMeta from abc import ABCMeta,abstractmethod class Foo():  __metaclass__ = ABCMeta  @abstractmethod  def bar(self):    pass

Running Effect

>>> class B(Foo):... def bar(self):... pass... >>> B()<__main__.B object at 0x02EE7B50>>>> B().bar()>>> class C(Foo):... pass... >>> C().bar()Traceback (most recent call last): File "<interactive input>", line 1, in <module>TypeError: Can't instantiate abstract class C with abstract methods bar>>> 


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.