Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:重载构造函数的问题_Python_Exception_Constructor Overloading - Fatal编程技术网

Python:重载构造函数的问题

Python:重载构造函数的问题,python,exception,constructor-overloading,Python,Exception,Constructor Overloading,警告:我已经学习Python整整10分钟了,所以对于任何愚蠢的问题,我深表歉意 我已经编写了以下代码,但是出现了以下异常: 消息文件 名称行位置回溯节点 31 exceptions.TypeError:此构造函数不接受任何参数 有什么想法吗?Python中的构造函数称为\uuuu init\uuu。您还必须使用“self”作为类中所有方法的第一个参数,并使用它来设置类中的实例变量 class Computer: def __init__(self, compName = "Comput

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

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

消息文件 名称行位置回溯节点 31 exceptions.TypeError:此构造函数不接受任何参数


有什么想法吗?

Python中的构造函数称为
\uuuu init\uuu
。您还必须使用“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)

这不是有效的python

Python类的构造函数是
def\uuu init\uuu(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)

首先,请看。

有许多事情需要指出:

  • Python中的所有实例方法都有一个显式的自参数
  • 构造函数称为
    \uuuu init\uuuu
  • 不能重载方法。通过使用默认方法参数,可以实现类似的效果
  • C++:

    class comp  {
      std::string m_name;
      foo(std::string name);
    };
    
    foo::foo(std::string name) : m_name(name) {}
    
    class comp:
      def __init__(self, name=None):
        if name: self.name = name
        else: self.name = 'defaultName'
    
    Python:

    class comp  {
      std::string m_name;
      foo(std::string name);
    };
    
    foo::foo(std::string name) : m_name(name) {}
    
    class comp:
      def __init__(self, name=None):
        if name: self.name = name
        else: self.name = 'defaultName'
    

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

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

    __init__()
    
    第二个问题是忘记在类方法中包含self参数

    此外,当您定义第二个构造函数时,您正在替换Computer()方法的定义。Python是非常动态的,可以让您重新定义类方法


    如果您不想将参数设置为必需的,则更具python风格的方法可能是为参数使用默认值。

    我假设您来自Java-ish背景,因此有一些关键区别需要指出

    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 "-----------------------------------------------------"
    

    伙计,给自己买本python书。潜入Python非常好

    Python不支持函数重载。

    printStatus有一个bug:它没有声明self.Ha!厄运!我们输入了相同的解决方案。感谢您的帮助,它非常有效!我真的认为我应该在开始之前读一本教程@TK:不,学习python如何工作没有什么错,特别是当你已经熟悉另一种语言的时候。水很好。你能看出我是个c#程序员吗?!是的,我现在意识到了。。。因为我至少在接下来的16个小时内都找不到一本真正的书,所以我想我应该马上投入进去。。。毕竟“有多难?!”找到一本在线书。这里有一个:今天的答案。清晰、高效、现实。请参阅