Mastering Object-oriented Python

Mastering Object-oriented Python

by
Steven F. Lott

Preface

Who this book is for

This is advanced Python.
This book doesn't introduce syntax or other foundational concepts.

Downloading the example code for this book


http://www.packtpub.com/support

Some Preliminaries


We will try to avoid digressing into the foundations of Python object-oriented programming.
We'll try to avoid repeating the presentation in Packt's Learning Python Design Patterns.

About casino Blackjack


二十一點(英文:Blackjack),是使用撲克牌玩的賭博遊戲。亦是賭場中莊家優勢在概率中最低的一種賭博遊戲。
二十一點的玩法:
  • 擁有最高點數的玩家獲勝,其點數必須等於或低於21點;超過21點的玩家稱為爆牌(Bust)
  • 2點至10點的牌以牌面的點數計算(number cards)
  • J、Q、K 每張為10點。(face cards)
  • A可記為1點或為11點, 若玩家會因A而爆牌則A可算為1點。當一手牌中的A算為11點時,這手牌便稱為「軟牌」(soft hand),因為除非玩者再拿另一張牌,否則不會出現爆牌。當一手牌中的A算為1點時,這手牌便稱為「硬牌」(hard hand)
  • 兩張牌點數相加為21(一張A再加一張價值10點的牌)稱為「二十一點」(black jack)。There are four two-card combinations that total 21
  • 莊家在取得17點之前必須要牌
  • 若玩家和莊家擁有同樣點數,這樣的狀態稱為「push」,玩家和莊家皆不算輸贏。每位玩者和莊家之間的遊戲都是獨立的,因此在同一局內,莊家有可能會輸給某些玩家,但也同時擊敗另一些玩家。

Object design for simulating Blackjack


As an example of object modeling:
  • one hand object will contain zero or more card objects.
  • the subclasses of Card : NumberCard, FaceCard, and Ace.

Performance – the timeit module


We'll make use of the timeit module to compare the actual performance of different object-oriented designs and Python constructs.




1. The __init__() Method


The implicit superclass – object


Each Python class definition has an implicit superclass: object .
It's a very simple class definition that does almost nothing.

The base class object __init__() method


We aren't required to implement __init__(). If we don't implement it, then no instance variables will be created when the object is created.

Implementing __init__() in a superclass


When an object is created, Python first creates an empty object and then calls the __init__() method for that new object.
This method function generally creates the object's instance variables and performs any other one-time processing.

class Card:
    def  __init__( self, rank, suit ):
        self.suit= suit
        self.rank= rank
        self.hard, self.soft = self._points()
           
class NumberCard( Card ):
    def _points( self ):
        return int(self.rank), int(self.rank)
        
class AceCard( Card ):
    def _points( self ):
        return 1, 11
    
class FaceCard( Card ):
    def _points( self ):
        return 10, 10
  • All the subclasses have identical signatures: they have the same methods and attributes.
  • inheritance
  • a common initialization in the superclass "Card"
  • polymorphism
  • Each subclass provides a unique implementation of the _points() method.

Using __init__() to create manifest constants


Leveraging __init__() via a factory function


Faulty factory design and the vague else clause






留言

熱門文章