Inheritance

The language feature most often associated with object-oriented programming is inheritance. Inheritance is the ability to define a new class that is a modified version of an existing class. It is called ‘inheritance’ because the new class inherits the methods of the existing class. Extending this metaphor, the existing class is called the parent class and the new class is called the child.

As an example, let’s say we want a class to represent a ‘hand’, that is, the set of cards held by one player. A hand is similar to a deck: both are made up of a set of cards, and both require operations like adding and removing cards. A hand is also different from a deck; there are operations we want for hands don’t make sense for a deck. For example, in poker we might compare two hands to see which wins. In bridge, we might compute a score for a hand in order to make a bid. This relationship between classes – similar, but different – lends itself to inheritance.

The definition of a child class is like other class definitions, but the name of the parent class appears in parentheses. The definition indicates that Hand inherits from Deck; that means we can use methods like pop_card and add_card for Hands as well as Decks. Hand also inherits the init method from Deck, but it doesn’t really do what we want: instead of populating the hand with 52 new cards, the init method for hands should initialize cards with an empty list. If we provide an init method in the Hand class, it overrides the one in the Deck class:

class Hand(Deck):
    """represents a hand of playing cards"""

    def __init__(self,label=‘‘):
        self.cards = []
        self.label = label

The next natural step is to encapsulate this code in a method called move_cards inside class Deck:

def move_card(self,hand,num):
        for i in range(num):
            hand.add_card(self.pop_card())

move_cards takes two arguments, a Hand object and the number of cards to deal. It modifies both self and hand, and returns None.

In some games, cards are moved from one hand to another, or form a hand back to the deck. You can use move_cards for any of these operations: self can be either a Deck or a Hand, and hand, despite the name, can also be a Deck.

Write a Deck method called deal hands that takes two parameters, the number of hands and the number of cards per hand, and that creates new Hand objects, deals the appropriate number of cards per hand, and returns a list of Hand objects.

def deal_hands(self,num_hands,num_cards):
        hands = list()
        for i in range(num_hands):
            hand = Hand()
            self.move_card(hand,num_cards)
            hands.append(hand)
        return hands

from Thinking in Python

时间: 2024-11-05 02:17:03

Inheritance的相关文章

Spring - Bean Definition Inheritance

A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name, and so on. A child bean definition inher

JAVA 面向对象-2-继承(Inheritance)

i.继承(Inheritance) 1.继承的概念 继承:在面向对象编程的过程中,通过扩展一个已有的类,并继承该类的属性和行为,来创建一个新的类. 继承是面向对象编程最重要的特征之一. 继承的优点:1). 避免大量的重复代码. 2). 继承是功能的拓展,使得结构清晰. 更容易维护和修改. 父类:之前已有的类,也可以称基类.超类(superClass)子类:新生的类,也可以叫派生类. 1.子类会继承父类的一切(不包括private修饰的私有类)方法和属性.2.Java中只能单继承,通过extend

Java Inheritance ( IS-A relationship)

Inheritance (IS-A) when a class extends another another class it inherits all non private members including fields and methods. Inheritence in Java can be best understood in terms of Parent and child relationship. also known as Super class and Sub cl

JavaPersistenceWithHibernate第二版笔记-第六章-Mapping inheritance-004Table per class hierarchy(@Inheritance..SINGLE_TABLE)、@DiscriminatorColumn、@DiscriminatorValue、@DiscriminatorFormula)

一.结构 You can map an entire class hierarchy to a single table. This table includes columns for all properties of all classes in the hierarchy. The value of an extra type discriminator column or formula identifies the concrete subclass represented by a

case class inheritance

Scala 禁止case class inheritance case class Person(name: String, age: Int) case class FootballPlayer(name: String, age: Int, number: Int) extends Person(name, age) 在编译时会报出以下错误: Error:(5, 12) case class FootballPlayer has case ancestor Person, but case-

【《Objective-C基础教程 》笔记ch04】(五)OC中的继承inheritance机制

一.为什么需要继承 使用继承一方面继承了父类的特性,另一方便解决了重复代码维护问题. 二.继承之语法 1. @interface 子类名:父类名 2. OC只支持单继承,不支持继承多个父类. 3. 重构--移植和优化代码. 三. 继承的工作机制 1. 方法调度 子类拥有一个指向它父类的引用指针,消息传递时,OC的方法调度机制使用该信息来找到正确的实现方法,查找过程是现在子类中找,找不到再到父类中继续找. 2. 实例变量 1)继承实例源码 @interface Shape : NSObject {

Chapter 17. Objects and Inheritance(对象与继承)

SELECT DISTINCT fa.application_short_name 模块,                 b.responsibility_name 职责名称, fa.application_name 应用产品,                 b.responsibility_key 责任关键字, b.description 说明,                 DECODE (b.data_group_id, 0, '标准', '') 数据组,              

Simple JavaScript Inheritance[转]

摘要:这篇文章介绍JavaScript的一种继承方式实现. 原文链接:https://johnresig.com/blog/simple-javascript-inheritance/ I've been doing a lot of work, lately, with JavaScript inheritance – namely for my work-in-progress JavaScript book – and in doing so have examined a number

a mechanism for code reuse in single inheritance languages

php.net 1 <?php 2 class Base { 3 public function sayHello() { 4 echo 'Hello'; 5 } 6 } 7 8 trait SayWorld { 9 public function sayHello() { 10 parent :: sayHello(); 11 echo 'World!'; 12 } 13 } 14 15 class MyHelloWorld extends Base { 16 use SayWorld; 17

Inheritance with EF Code First: Part 2 – Table per Type (TPT)

In the previous blog post you saw that there are three different approaches to representing an inheritance hierarchy and I explained Table per Hierarchy (TPH) as the default mapping strategy in EF Code First. We argued that the disadvantages of TPH m