【发布时间】:2018-11-16 23:08:35
【问题描述】:
我希望用户能够通过传递参数来启动一个类,如果他没有传递它,那么它应该由类自动创建。这通常在 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'
编辑:self.argm 将是 python-docx Object,所以我无法做到 def __init__(self, argument = Document() 还是我?
【问题讨论】:
-
def __init__(self, argument='some_value'): -
既然您已经知道如何创建默认参数,这应该可以回答您的问题:Python optional parameters
-
@Aran-Fey thx 链接,我将使用
argument=None进行初始化并检查它在 init 中的值。谢谢!
标签: python class optional-arguments