习题35:物以类聚

发布时间:2017-11-23 17:04:44编辑:Run阅读(5198)

    Class(类)有着各种各样强大的功能和用法

    用到"class"的编程语言被称为"Object Oriented Programming(面向对象编程)"语言,这是一种传统的编程方式,你需要做出'东西'来,然后你'告诉'这些东西取完成它们的工作

    stuff = ['test','this','out']

    print(''.join(stuff))

    testthisout

    其实这里已经使用了class. ‘stuff’这个变量其实是一个list class(列表类),而''.join(stuff)里调用函数join的字符串''(就是一个空格)也是一个class----它是一个string class(字符串类),到处都是class

    怎样创建class呢?代码如下

    # coding: utf-8
    __author__ = 'www.py3study.com'
    class Thething(object):
        def __init__(self):
            self.number = 0
    
        def some_function(self):
            print("I got called.")
    
        def add_me_up(self, more):
            self.number += more
            return self.number
    
    # two different things
    a = Thething()
    b = Thething()
    a.some_function()
    b.some_function()
    
    print(a.add_me_up(20))
    print(b.add_me_up(30))
    print(a.number)
    print(b.number)
    
    # Study this. This is how you pass a variable
    # from one class to another. You will need this
    class TheMultiplier(object):
        def __init__(self, base):
            self.base = base
    
        def do_it(self, m):
            return m * self.base
    
    x = TheMultiplier(a.number)
    print(x.do_it(b.number))

    你应该看到的结果

    图片.png

关键字