New writing for Python abstract classes

Source: Internet
Author: User

This article mainly introduces the new writing of Python abstract class, this article explained the old version of the hack way to implement the abstract class, and 2.7 use Abstractmethod module to write abstract class method, need friends can refer to the following

Remember the previous learn Python book, because there was no official support, only through the hack way to implement abstract methods, the following is the simplest method

?

1 2 3 4 5 6 7 8 9 10 11 Class Mycls (): def foo (self): example of the run of print (' method no implement ') >>> a = Mycls () >>> A.foo () metho D No implement >>>

This can be used, but the hint is not obvious, or easy to misuse, of course, there are better ways to accept the wording

?

1 2 3 Class Mycls (): def foo (self): Raise Exception (' No implement Exception ', ' Foo method need implement ')

A simple use case

?

1 2 3 4 5 6 >>> a = Mycls () >>> A.foo () traceback (most recent call last): File "<interactive input>", line 1, In <module> File "<clipboard>", line 3, in Foo Exception: (' No implement Exception ', ' Foo method need impleme NT ')

This is what was written before 2.7, and 2.7 gives us the new support Method!ABC Module (abstruct base Class), which has been implemented in py3k, is the back port.

Let's take a look at the new wording.

?

1 2 3 4 5 6 7 8 9 From ABC import abcmeta from ABC import Abcmeta,abstractmethod class Foo (): __metaclass__ = Abcmeta @abstractmethod de F Bar (self): Pass

Run effect

?

1 2 3 4 5 6 7 8 9/ >>> 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 Abstrac T class C with abstract methods bar >>>

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.