开发者

Can I declare a class within a function in Python?

How can I define class Options inside of my CheckForJiraIssueRecord function?

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=开发者_如何学Go "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);

Is it possible to declare classes within functions in Python?


Yes, just correct your indentation and that code should work. You'll be creating a new class each time the function is called.

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

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


Yes, however:

1) Each time through the function, Options becomes a separate class. Not that you will really be able to write code that exploits (or is broken by) this property, because

2) You can only instantiate the class via the function, unless you explicitly expose it to the global namespace somehow.

3) Assuming that you just need an object with those attributes - i.e. Jira doesn't care about your class interface beyond being able to do .user and .password - you don't really need to create a custom class at all:

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...


Yes, you can. Although each time the function is called, you will get a different class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜