Python object-oriented Programming--__init () __ Method

Source: Internet
Author: User
Tags inheritance

Implicitly-based class object

Each Python class implicitly inherits an object

Full-Text Code example implementation: enumeration of Poker's suit and card face value

One, _init () __ Method: Object Initialization

Display instead of implicit: __init () __ should show initialization variables

When an object is instantiated, an empty object is created before calling __init () __ to initialize the object's internal variables or other content.

Second, _init () __ Method use case:

  (i) Base class implementation initialization


1 classCard:2 def __init__(self, Rank, suit):3Self.rank =Rank4Self.suit =Suit5Self.hard, Self.soft =self._points ()6 7 8 classNumbercard (Card):9 def_points (self):Ten returnInt (self.rank), int (Self.rank) One A - classAcecard (Card): - def_points (self): the return1, 11 - - - classFacecard (Card): + def_points (self): - return10, 10
    • Three sub-classes share common initialization logic
    • Polymorphic: Three subclasses have different function implementations for _points (self)

 Improved: Subclass implementation __init () __ Method

1 classCard:2     def __init__(self, rank, suit, hard, soft):3Self.rank =Rank4Self.suit =Suit5Self.hard = Hard6Self.soft =Soft7 8 9 classNumbercard (Card):Ten     def __init__(self, Rank, suit): OneSuper ().__init__(str (rank), suit, rank, rank) A  -  - classAcecard (Card): the     def __init__(self, Rank, suit): -Super ().__init__('A', suit, 1, 11) -  -  + classFacecard (Card): -     def __init__(self, Rank, suit): +Super ().__init__({1:'A', 11:'J', 12:'Q', 13:'K'}[rank], suit, 10, 10)

Super (): When a subclass is used to invoke a method with the same name as the parent class

Single Inheritance:

Call Super () directly in the same name function. Fun_name ()

Multiple inheritance:

Call super directly in the same name function (to call the previous class name of a parent class, self). Fun_name ()

  (ii) Create a list of constants

# the character and name of the card class Suit:     def __init__ (self, Name, symbol):         = name        = Symbol

1Club, Diamond, heart, Spade = Suit ('Club','C'), Suit ('Diamond','D'),2Suit ('Heart','H'), Suit ('Spade','S')
called

Second, the factory function

Two ways to implement factory functions

    • Defines a function that returns objects of different classes
    • Defines a class that contains methods for creating objects

Pathway One:

1 defcard1 (rank, suit):2     ifRank = = 1:3         returnAcecard ('A', suit)4     elif2 <= Rank <= 10:5         returnNumbercard (str (rank), suit)6     elifRank = = 11:7         returnFacecard ('J', suit)8     elifRank = = 12:9         returnFacecard ('Q', suit)Ten     elifRank = = 13: One         returnFacecard ('K', suit)

The above function realizes the match of the card face value and the suit

Iii. using maps and classes to simplify design

  (i) Parallel mapping

1 defCard2 (rank, suit):2     #find rank in the collection, not found to return Numbercard3Class_ = {1:acecard, 11:facecard, 12:facecard, 13: Facecard}.get (rank,4 Numbercard)5Rank_str = {1:'A', 11:'J', 12:'Q', 13:'K'}.get (rank, str )6     returnClass_ (RANK_STR, suit)

Cons: Mapping keys 1, 11, 12, 13, logical repetition, using two-time mappings to obtain the face value and color of the card. Duplicated code is redundant and improves maintenance costs

  (ii) two-tuple mapping

1 #Two tuple mappings2 defCard3 (rank, suit):3Class_, rank_str = {1: (Acecard,'A'), one: (Facecard,'J'),: (Facecard,'Q'),4: (Facecard,'K')}.get (rank, (Numbercard, str (rank)))5     returnClass_ (RANK_STR, suit)

  (iii) Partial function: partial function

How to use: Call function Fun_name (arg1,arg* ...)

Fun_name1=partial (Fun_name, arg1 ...)

Fun_name1 (arg* ...) partial function

 fromFunctoolsImportPartialdefCard4 (rank, suit): Part_class= {1:partial (Acecard,'A'), 11:partial (Facecard,'J'),                  12:partial (Facecard,'Q'), 13:partial (Facecard,'K')}. Get (rank, partial (numbercard, str ))returnPart_class (SUIT)

(iv) Factory fluent API

The API is implemented in conjunction with a two-tuple map, which sequentially invokes

1 classcardfactory:2     defrank (self, rank):3Self.class_, Self.rank_str = {41: (Acecard,'A'),5One: (Facecard,'J'),6: (Facecard,'Q'),7: (Facecard,'K')8 }.get (rank, (Numbercard, str (rank)))9         return SelfTen  One     defsuit (self, suit): A         returnSelf.class_ (SELF.RANK_STR, suit)

Python object-oriented Programming--__init () __ Method

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.