2018-12-06

2018-12-06  本文已影响0人  Karl_2c80

类的属性-总结

#!/usr/bin/python
#coding:utf8


var6 = '全局变量 var6'

class MyClass(object):
    var1 = '类属性 var1'
    __var2 = '类的私有属性 __var2'

    def func1(self):
        self.var3 = '对象的共有属性 var3'
        self.__var4 = '对象的私有属性 __var4'
        var5 = '函数的局部变量 var5'


mc = MyClass()
mc.func1()
print mc.var3
mc2 = MyClass()
print mc2.var3
[root@KARL ~]# python u4.py
对象的共有属性 var3
Traceback (most recent call last):
  File "u4.py", line 21, in <module>
    print mc2.var3
AttributeError: 'MyClass' object has no attribute 'var3'

类的方法-总结

#!/usr/bin/python
#coding:utf8

class MyClass(object):
    name = 'Test'

    def __init__(self):
        self.func1()
        self.__func2()
        self.classFunc()
        # staticFunc()  # 静态方法不带self,且不能在构造方法中直接调用

    def func1(self):
        print self.name,
        print "我是公有方法"

    def __func2(self):
        print self.name,
        print "我是私有方法"

    @classmethod
    def classFunc(self):
        print self.name,
        print "我是类方法"

    @staticmethod
    def staticFunc():
        #print self.name,
        print "我是静态方法"

mc = MyClass()
print '#'*50
mc.func1()
mc._MyClass__func2()
mc.classFunc()
mc.staticFunc()         # 可通过对象来调用静态方法
[root@KARL ~]# python u5.py
Test 我是公有方法
Test 我是私有方法
Test 我是类方法
##################################################
Test 我是公有方法
Test 我是私有方法
Test 我是类方法
我是静态方法

rc脚本(类的定义与脚本的结构)

#!/usr/bin/python
#coding:utf8

import sys

class Process(object):
    '''memcached rc script'''
    def __init__(self, name, program, args, workdir):
        self.name = mame
        self.program = program
        self.args = args
        self.workdir = workdir

    def _init(self):    # 不是私有方法


    def start(self):

    def stop(self):

    def restart(self):
        self.stop()
        self.start()

    def status(self):

    def help(self):

def main():
    name = 'memcached'
    program = '/usr/bin/memcached'
    args = '-u nobody -p 11211 -c 1024 -m 64'
    wd = '/var/tmp/memcached'
    pm = Process(name = name,
                 program = prog,
                 args = args,
                 workdir = wd)
    try:
        cmd = sys/.argv[1]
    except IndexError, e:
        print "Option error"
        sys.exit()
    if cmd == 'start':
        pm.start()
    elif cmd == 'stop':
        pm.stop()
    elif cmd == 'restart':
        pm.restart()
    elif cmd == 'status':
        pm.status()
    else:
        pm.help()


if __name__ == '__main__':
    main()
上一篇下一篇

猜你喜欢

热点阅读