1、创建类
#!/usr/bin/pythonclass person: passp = person() # 引用类print p[root@saltstack python]# python class1.py <__main__.person instance at 0x7f716751ae18>
2、类的调用方法
#!/usr/bin/pythonclass person: def sayHi(self): name = raw_input('Enter input your name: ') print 'Hello %s, how are you?' % namep = person() # 调用类p.sayHi() # 调用函数[root@saltstack python]# python class2.py Enter input your name: hhHello hh, how are you?[root@saltstack python]# cat class2.py
3、init
'''# __init__方法在类的一个对象被建立时,这个方法可以用来对你的对象做一些你希望的 初始化'''
#!/usr/bin/pythonclass person: def __init__(self,name): self.name = name def sayHi(self): print 'Hello, my name is ', self.namep = person('Swaroop')p.sayHi()[root@saltstack python]# python init.pyHello, my name is Swaroop# 或#!/usr/bin/pythonclass person: def __init__(self, name): self.n = name # self.n为自定义 def sayHi(self): print 'Hello, my name is ', self.np = person('hhhh')p.sayHi()[root@saltstack python]# python init.py Hello, my name is hhhh
3、使用类与对象的变量
#!/usr/bin/pythonclass person: population = 0 def __init__(self,name): self.name = name print '(Initializing %s)' % self.name person.population += 1 def __del__(self): print '%s says bye.' % self.name person.population -= 1 if person.population == 0: print 'I an the last one.' else: print 'There are still %d people left.' % person.population def sayHi(self): print 'Hi, my name is %s.' % self.name def howMany(self): if person.population == 1: print 'I am the only person here.' else: print 'We have %d persons here.' % person.populationswaroop = person('Swaroop')swaroop.sayHi()swaroop.howMany()kalam = person('Abdul kalam')kalam.sayHi()kalam.howMany()swaroop.sayHi()# 执行[root@saltstack python]# python class3.py (Initializing Swaroop)Hi, my name is Swaroop.I am the only person here.(Initializing Abdul kalam)Hi, my name is Abdul kalam.We have 2 persons here.Hi, my name is Swaroop.Abdul kalam says bye.There are still 1 people left.Swaroop says bye.I an the last one.
4、sys模块
#!/usr/bin/env pythonimport sysfilename = sys.argv[1]f = file(filename)while True: line = f.readline() if len(line) == 0: break print linef.close()[root@saltstack python]# python sys.py 1.py#!/usr/bin/pythonaDict = {'host': 'earth'}aDict['port'] = 80for key in aDict: print key, aDict[key]