Python:重载构造函数的问题

发布于 2024-07-09 22:36:29 字数 936 浏览 10 评论 0原文

警告:我已经学习 Python 10 分钟了,所以对于任何愚蠢的问题深表歉意!

我编写了以下代码,但是出现以下异常:

消息文件 名称行位置追溯节点 31 异常。类型错误:此构造函数不带参数

class Computer:

    name = "Computer1"
    ip = "0.0.0.0"
    screenSize = 17


    def Computer(compName, compIp, compScreenSize):
        name = compName
        ip = compIp
        screenSize = compScreenSize

        printStats()

        return

    def Computer():
        printStats()

        return

    def printStats():
        print "Computer Statistics: --------------------------------"
        print "Name:" + name
        print "IP:" + ip
        print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects
        print "-----------------------------------------------------"
        return

comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)

有什么想法吗?

WARNING: I have been learning Python for all of 10 minutes so apologies for any stupid questions!

I have written the following code, however I get the following exception:

Message File
Name Line Position Traceback Node
31
exceptions.TypeError: this constructor takes no arguments

class Computer:

    name = "Computer1"
    ip = "0.0.0.0"
    screenSize = 17


    def Computer(compName, compIp, compScreenSize):
        name = compName
        ip = compIp
        screenSize = compScreenSize

        printStats()

        return

    def Computer():
        printStats()

        return

    def printStats():
        print "Computer Statistics: --------------------------------"
        print "Name:" + name
        print "IP:" + ip
        print "ScreenSize:" , screenSize // cannot concatenate 'str' and 'tuple' objects
        print "-----------------------------------------------------"
        return

comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)

Any thoughts?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

生生不灭 2024-07-16 22:36:29

我假设您有 Java 背景,因此需要指出一些关键差异。

class Computer(object):
    """Docstrings are used kind of like Javadoc to document classes and
    members.  They are the first thing inside a class or method.

    You probably want to extend object, to make it a "new-style" class.
    There are reasons for this that are a bit complex to explain."""

    # everything down here is a static variable, unlike in Java or C# where
    # declarations here are for what members a class has.  All instance
    # variables in Python are dynamic, unless you specifically tell Python
    # otherwise.
    defaultName = "belinda"
    defaultRes = (1024, 768)
    defaultIP = "192.168.5.307"

    def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP):
        """Constructors in Python are called __init__.  Methods with names
        like __something__ often have special significance to the Python
        interpreter.

        The first argument to any class method is a reference to the current
        object, called "self" by convention.

        You can use default function arguments instead of function
        overloading."""
        self.name = name
        self.resolution = resolution
        self.ip = ip
        # and so on

    def printStats(self):
        """You could instead use a __str__(self, ...) function to return this
        string.  Then you could simply do "print(str(computer))" if you wanted
        to."""
        print "Computer Statistics: --------------------------------"
        print "Name:" + self.name
        print "IP:" + self.ip
        print "ScreenSize:" , self.resolution //cannot concatenate 'str' and 'tuple' objects
        print "-----------------------------------------------------"

I'm going to assume you're coming from a Java-ish background, so there are a few key differences to point out.

class Computer(object):
    """Docstrings are used kind of like Javadoc to document classes and
    members.  They are the first thing inside a class or method.

    You probably want to extend object, to make it a "new-style" class.
    There are reasons for this that are a bit complex to explain."""

    # everything down here is a static variable, unlike in Java or C# where
    # declarations here are for what members a class has.  All instance
    # variables in Python are dynamic, unless you specifically tell Python
    # otherwise.
    defaultName = "belinda"
    defaultRes = (1024, 768)
    defaultIP = "192.168.5.307"

    def __init__(self, name=defaultName, resolution=defaultRes, ip=defaultIP):
        """Constructors in Python are called __init__.  Methods with names
        like __something__ often have special significance to the Python
        interpreter.

        The first argument to any class method is a reference to the current
        object, called "self" by convention.

        You can use default function arguments instead of function
        overloading."""
        self.name = name
        self.resolution = resolution
        self.ip = ip
        # and so on

    def printStats(self):
        """You could instead use a __str__(self, ...) function to return this
        string.  Then you could simply do "print(str(computer))" if you wanted
        to."""
        print "Computer Statistics: --------------------------------"
        print "Name:" + self.name
        print "IP:" + self.ip
        print "ScreenSize:" , self.resolution //cannot concatenate 'str' and 'tuple' objects
        print "-----------------------------------------------------"
忘羡 2024-07-16 22:36:29

Python 中的构造函数称为__init__。 您还必须使用“self”作为类中所有方法的第一个参数,并使用它来设置类中的实例变量。

class Computer:

    def __init__(self, compName = "Computer1", compIp = "0.0.0.0", compScreenSize = 22):
        self.name = compName
        self.ip = compIp
        self.screenSize = compScreenSize

        self.printStats()

    def printStats(self):
        print "Computer Statistics: --------------------------------"
        print "Name:", self.name
        print "IP:", self.ip
        print "ScreenSize:", self.screenSize
        print "-----------------------------------------------------"


comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)

Constructors in Python are called __init__. You must also use "self" as the first argument for all methods in your class, and use that to set instance variables in the class.

class Computer:

    def __init__(self, compName = "Computer1", compIp = "0.0.0.0", compScreenSize = 22):
        self.name = compName
        self.ip = compIp
        self.screenSize = compScreenSize

        self.printStats()

    def printStats(self):
        print "Computer Statistics: --------------------------------"
        print "Name:", self.name
        print "IP:", self.ip
        print "ScreenSize:", self.screenSize
        print "-----------------------------------------------------"


comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
执妄 2024-07-16 22:36:29

伙计,给自己买一本Python书吧。 深入研究 Python 非常好。

dude get yourself a python book. Dive into Python is pretty good.

耀眼的星火 2024-07-16 22:36:29

那不是有效的 python。

Python 类的构造函数是 def __init__(self, ...): 并且您不能重载它。

您可以做的是使用参数的默认值,例如。

class Computer:
    def __init__(self, compName="Computer1", compIp="0.0.0.0", compScreenSize=17):
        self.name = compName
        self.ip = compIp
        self.screenSize = compScreenSize

        self.printStats()

        return

    def printStats(self):
        print "Computer Statistics: --------------------------------"
        print "Name      : %s" % self.name
        print "IP        : %s" % self.ip
        print "ScreenSize: %s" % self.screenSize
        print "-----------------------------------------------------"
        return

comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)

That isn't valid python.

The constructor for a Python class is def __init__(self, ...): and you cannot overload it.

What you can do is use defaults for the arguments, eg.

class Computer:
    def __init__(self, compName="Computer1", compIp="0.0.0.0", compScreenSize=17):
        self.name = compName
        self.ip = compIp
        self.screenSize = compScreenSize

        self.printStats()

        return

    def printStats(self):
        print "Computer Statistics: --------------------------------"
        print "Name      : %s" % self.name
        print "IP        : %s" % self.ip
        print "ScreenSize: %s" % self.screenSize
        print "-----------------------------------------------------"
        return

comp1 = Computer()
comp2 = Computer("The best computer in the world", "27.1.0.128",22)
情愿 2024-07-16 22:36:29

首先,请查看此处

For a start, look here.

贪恋 2024-07-16 22:36:29

有很多事情需要指出:

  1. Python 中的所有实例方法都有一个显式的 self 参数。
  2. 构造函数称为__init__
  3. 您不能重载方法。 您可以通过使用默认方法参数来实现类似的效果。

C++:

class comp  {
  std::string m_name;
  foo(std::string name);
};

foo::foo(std::string name) : m_name(name) {}

Python:

class comp:
  def __init__(self, name=None):
    if name: self.name = name
    else: self.name = 'defaultName'

There are a number of things to point out:

  1. All instance methods in Python have an explicit self argument.
  2. Constructors are called __init__.
  3. You cannot overload methods. You can achieve a similar effect by using default method arguments.

C++:

class comp  {
  std::string m_name;
  foo(std::string name);
};

foo::foo(std::string name) : m_name(name) {}

Python:

class comp:
  def __init__(self, name=None):
    if name: self.name = name
    else: self.name = 'defaultName'
向日葵 2024-07-16 22:36:29

啊,这些是新 Python 开发人员常见的问题。

首先,应该调用构造函数:

__init__()

第二个问题是忘记将 self 参数包含到类方法中。

此外,当您定义第二个构造函数时,您将替换 Computer() 方法的定义。 Python 非常动态,并且很乐意让您重新定义类方法。

如果您不想使参数成为必需的,更Pythonic 的方法可能是使用参数的默认值。

Ah, these are common gotchas for new python developers.

First, the constructor should be called:

__init__()

Your second issue is forgetting to include the self parameter to your class methods.

Furthermore, when you define the second constructor, you're replacing the definition of the Computer() method. Python is extremely dynamic and will cheerfully let you redefine class methods.

The more pythonic way is probably to use default values for the parameters if you don't want to make them required.

隐诗 2024-07-16 22:36:29

Python 不支持函数重载。

Python does not support function overloading.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文