#!/usr/bin/python
#coding:utf-8
#类的使用
#真的用该好好学习下类的使用(今天才恍然大悟类可以这样使用)




#定义个一个基类
class State(object):
    def __init__(self):
        self.states = {}


    def add_state(self,state):
        'state 是一个实例的'
        self.states[state.name] = state


class Name(object):
    def __init__(self,name):
        self.name = name


    def r_print(self):
        print 'hello %s'%self.name




state = State()
for i in range(1,10):
    state.add_state(Name(i))




>>> state.states
{1: <__main__.Name object at 0x093B5090>,
2: <__main__.Name object at 0x0C90DFD0>,
3: <__main__.Name object at 0x0C90DCF0>,
4: <__main__.Name object at 0x0C90DED0>,
5: <__main__.Name object at 0x0C8FA070>,
6: <__main__.Name object at 0x0C91A030>,
7: <__main__.Name object at 0x0C91A050>,
8: <__main__.Name object at 0x0C91A070>,
9: <__main__.Name object at 0x0C91A090>}
>>> state.states[1]
<__main__.Name object at 0x093B5090>
>>> state.states[1].r_print()
hello 1
>>> state.states[2].r_print()
hello 2
>>> state.states[3].r_print()
hello 3
>>> state.states[4].r_print()
hello 4
>>> state.states[5].r_print()
hello 5
>>>


…………
以后可以操作类进行写代码了(又简化了许多)
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐