第七章 类与可口可乐

    All the Cokes are the same and all the Cokes are good. Liz Taylor > knows it, the President knows it, the bum knows it, and you know > it. ——Andy Warhol

    第七章 类与可口可乐 - 图1

    “在美国,所有人喝到的可乐的都是一样的,无论是总统或者是流浪汉”。波普艺术家 Andy Warhol 如是说。如果用编程的语言来表达 Andy 的思想,那么我想可能用类(class)这个概念最为合适。

    class CocaCola():
    it_taste = 'So good!'
    coke_for_bum = CocaCola()
    coke_for_president = CocaCola()
    print(coke_for_bum.it_taste)
    print(coke_for_president.it_taste)

    运行结果:

    >>> So good!
    >>> So good!

    第七章 类与可口可乐 - 图2

    怎么样?无论是 Andy Warhol 的波普艺术的理念,还是 Python 中的类的概念,看起来似乎都没有那么难理解。即便你现在对类还充满疑惑,但是我相信,在学习了这一章之后,你将会很好地理解类中那些令人费解的概念。同时,这一章将会使用可乐来讲解关于类的各种概念,实际上编程中的概念都可以在现实生活中找到很好的例子进行对照理解,为了加强理解,你最好现在出门买一瓶可乐,然后开始接下来的学习!