【问题标题】:How to write a python class that is initialized with either no arguments or one argument如何编写一个没有参数或一个参数初始化的python类
【发布时间】:2017-12-07 20:34:16
【问题描述】:

我正在从 Java 过渡到 Python,目前被这个看似简单的代码难住了,它的 Java 等效代码运行良好。

我正在尝试创建一个名为 TestClass 的对象,它要么接受一个名为 text 的参数,要么不接受任何参数;在这种情况下,会将默认字符串“foo”分配给文本实例变量。

class TestClass(object):

   def __init__(self):
      self.text = "foo"

   def __init__(self, text):
      self.text = text


a = TestClass()
b = TestClass("bar")

我真的无法查明问题并得到以下错误:

a = TestClass()

TypeError: init() 缺少 1 个必需的位置参数:'text

您的帮助将不胜感激,谢谢!

【问题讨论】:

  • 默认参数:def __init__(self, text="foo"):done
  • 很好用!

标签: python typeerror


【解决方案1】:

Java 没有参数的默认值(至少上次我检查过)

在 Python 中,您不能覆盖具有不同参数的方法(这是可能的,但第一个定义变得不可见,所以这不是很有用)。

所以你想要做的翻译如下:

def __init__(self, text="foo"):
   self.text = text

字符串、整数、浮点数都可以,但要小心可变类型:"Least Astonishment" and the Mutable Default Argument

另外,如果你想用不同的参数types“模拟”相同的方法名,你必须定义一个方法(不会改变)并使用动态类型检查来决定做什么:

def __init__(self, param):
   if isinstance(param,str):
       # param is a string
   elif isinstance(param,int):
       # param is an integer

【讨论】:

    猜你喜欢
    • 2019-01-26
    • 2011-08-05
    • 2018-01-27
    • 2021-04-25
    • 1970-01-01
    • 2021-05-17
    • 2012-03-02
    • 2019-11-04
    • 1970-01-01
    相关资源
    最近更新 更多