我可以在Python中的函数中声明一个类吗?

时间:2011-09-21 20:56:51

标签: python

如何在class Options函数中定义CheckForJiraIssueRecord

def CheckForJiraIssueRecord(object):
    #sys.stdout = open(os.devnull)
    #sys.stderr = open(os.devnull)

    class Options:
        pass
    options = Options()

    options.user = 'user'
    options.password = 'password'

    try:
        com = jira.Commands()
        logger = jira.setupLogging()
        jira_env = {'home':os.environ['HOME']}
        command_cat= "cat"
        server = "http://jira.server.com:8080/rpc/soap/jirasoapservice-v2?wsdl"
    except Exception, e:
        sys.exit('config error')
    try:
        jira.soap = jira.Client(server)
        jira.start_login(options, jira_env, command_cat, com, logger)
        issue = com.run(command_cat, logger, jira_env, my_args)
    except Exception, e:
        print sys.exit('data error')

if __name__ == '__main__':
    commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"'))
    #commit_text_verified = verify_commit_text(os.popen('hg log -r $1  --template "{desc}"'))
    if (commit_text_verified):
        sys.exit(0)
    else:
        print >> sys.stderr, ('[obey the rules!]')
        sys.exit(1);

是否可以在Python中的函数中声明类?

3 个答案:

答案 0 :(得分:6)

是的,只需更正您的缩进,该代码应该有效。每次调用函数时,您都将创建一个新类。

def CheckForJiraIssueRecord(object):
    class Options:
        pass
    options = Options()

    options.user = 'user'
    options.password = 'password'

答案 1 :(得分:2)

是的,你可以。虽然每次调用函数时,您都会得到一个不同的类。

答案 2 :(得分:2)

是的,但是:

1)每次通过该功能,Options成为一个单独的类。并不是说您真的能够编写利用此属性(或被其破坏)的代码,因为

2)你只能通过函数实例化类,除非你以某种方式明确地将它暴露给全局命名空间。

3)假设您只需要一个具有这些属性的对象 - 即Jira不关心您的类界面,除了能够.user.password - 你真的不需要根本创建一个自定义类:

from collections import namedtuple
def CheckForJiraIssueRecord(object):
    options = namedtuple('Options', 'user password')('user', 'password')
    # 'user password' are the field names, and ('user', 'password') are the
    # initialization values. This code creates a type similar to what you had
    # before, naming it 'Options' internally, but doesn't bind it to a variable.

    # As you were...