Python类:可选参数

2024-04-16 21:08:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户能够通过向类传递参数来初始化类,如果他不传递参数,那么应该由类自动创建。在Python中通常是如何实现的?示例:

class MyClass(object):

    def __init__(self, argument):

        self.argm = argument
        # logic here: if user does not pass argument
        # run some function or do something


    def create_argm(self):

        self.argm = 'some_value'



object_example = MyClass()
print(object_example.argm) # will print 'some_value'

object_example = MyClass('some_other_value')
print(object_example) # will print 'some_other_value'

编辑:自身参数会是python-docx Object所以我不能做def __init__(self, argument = Document()还是我?你知道吗


Tags: 用户self参数objectinitvalueexampledef
2条回答

这通常通过为关键字参数指定默认值来完成:

class MyClass(object):

    def __init__(self, argument='default value'):
        self.argm = argument

如果希望此默认值是可变对象,则必须特别注意;这可能会导致不需要的行为,因为对象只会创建一次,然后会发生变化。你知道吗

如果无法在函数定义中创建值,则可以使用不表示任何内容的值,幸运的是python有None,因此可以执行以下操作:

class MyClass(object):
    def __init__(self, argument=None):
        if argument is None:
            self.argm = self.create_argm()
        else:
            self.argm = argument

    def create_argm(self):
        return 'some_value'

如果None不适合,因为您希望它是argument的有效值,而不假定它被忽略,则始终可以创建一个伪值:

class MyNone:
    pass

class MyClass(object):
    def __init__(self, argument=MyNone):
        if argument is MyNone:
            self.argm = self.create_argm()
        else:
            self.argm = argument

    def create_argm(self):
        return 'some_value'

相关问题 更多 >