Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
489 views
in Technique[技术] by (71.8m points)

optional arguments in initializer of python class

I was wondering if anyone had any good ways of quickly explaining how to efficiently and pythonically create user defined objects with optional arguments. For instance, I want to create this object:

class Object:
    def __init__(self, some_other_object, i, *j, *k):
        self.some_other_object = some_other_object
        self.i = i
        # If j is specified, assume it is = i
        if(j==None):
            self.j = i
        else:
            self.j = j
        # If k is given, assume 0
        if(k==None):
            self.k = 0
        else:
            self.k = k

Is there a better way to do this?

EDIT: I changed the code so that it is more broad and more easily understood.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can set default parameters:

class OpticalTransition(object):
    def __init__(self, chemical, i, j=None, k=0):
        self.chemical = chemical
        self.i = i
        self.k = k
        self.j = j if j is not None else i

If you don't explicitly call the class with j and k, your instance will use the defaults you defined in the init parameters. So when you create an instance of this object, you can use all four parameters as normal: OpticalTransition('sodium', 5, 100, 27)

Or you can omit the parameters with defaults with OpticalTransition('sodium', 5), which would be interpreted as OpticalTransition('sodium', 5, None, 0)

You can use some default values but not all of them as well, by referencing the name of the parameter: OpticalTransition('sodium', 5, k=27) uses j's default but not k's.

Python won't allow you to do j=i as a default parameter (i isn't an existing object that the class definition can see), so the self.j line handles this with an if statement that in effect does the same thing.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...