您的位置:首页 > 编程语言 > Python开发

Learn Python The Hard Way exercise 42

2014-05-25 23:27 351 查看
这个练习有些困惑,在Zed建立的模式里大概了解一下object和class的区别吧。

比较重要的观点是

    Mary is a kind of Salmon that is a kind of Fish. object is a class is a class.

   you need to learn two catch phrases: “is- a” and “has- a.”

   You use the phrase is- a when you talk about objects and classes being related to each other by a class relationship. You use has- a when you talk about objects and     classes that are related only because they reference each other.(这句着实不明白,但是不明觉厉,此中估计有真意,假以时日,再来啃。)

    assume that Python always requires (object) when you make a class. 

以下是我的答案

## Dog is-a Animal
class Dog(Animal):

def __init__(self, name):
##Dog has a self and name

## Cat is-a Animal
class Cat(Animal):

def __init__(self, name):
## Cat has-a self and name
self.name = name

## Person is-a object
class Person(object):

def __init__(self, name):
## Person has-a self and name
self.name = name

## Person has-a pet of some kind
self.pet = None

## Employee is-a Person
class Employee(Person):

def __init__(self, name, salary):
##
super(Employee, self).__init__(name)
## Employee has-a salary
self.salary = salary

## Fish is-a object
class Fish(object):
pass

## Salmon is-a Fish
class Salmon(Fish):
pass

## Halibut is-a Fish
class Halibut(Fish):
pass

## rover is-a Dog
rover = Dog("Rover")

## satan is-a Cat
satan = Cat("Satan")

## mary is-a Person
mary = Person("Mary")

## mary has-a pet named satan ???????????
mary.pet = satan

## Frank has-a salary of 120000
frank= Employee("Frank", 120000)

## frank has-a pet
frank.pet = rover

## flipper is-a attribute of Fish
flipper = Fish()

## crouse is-a attribute of Salmon
crouse = Salmon()

## harry is-a attribute of Halibut
harry = Halibut()

末了,还是不甘心就这样糊里糊涂的过去,找来一些解释。
具体见《How
to Think Like a Computer Scientist: Learning with Python 2nd Edition documentation》

class
A user-defined compound type. A class can also be thought of as a template for the objects that are instances of it.
instantiate
To create an instance of a class.
instance
An object that belongs to a class.
object
A compound data type that is often used to model a thing or concept in the real world.
attribute
One of the named data items that makes up an instance.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: