相关疑难解决方法(0)

如何基于参数类型重载__init__方法?

假设我有一个类,其成员名为data,这是一个列表.

我希望能够使用例如文件名(包含初始化列表的数据)或实际列表来初始化类.

你这样做的技巧是什么?

你只是看看类型__class__吗?

我可能会缺少一些技巧吗?

我已经习惯了C++,其中按参数类型重载很容易.

python constructor operator-overloading

297
推荐指数
5
解决办法
15万
查看次数

Python:重载构造函数的问题

警告:我一直在学习Python 10分钟,所以对任何愚蠢的问题表示歉意!

我写了以下代码,但是我得到以下异常:

消息文件名行位置跟踪节点31 exceptions.TypeError:此构造函数不带参数

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)
Run Code Online (Sandbox Code Playgroud)

有什么想法吗?

python exception constructor-overloading

7
推荐指数
2
解决办法
5226
查看次数