2008-11-23 3 views
7

ВНИМАНИЕ: Я изучаю Python на все 10 минут, поэтому приношу извинения за любые глупые вопросы!Python: проблема с перегруженными конструкторами

Я написал следующий код, но я получаю следующее исключение:

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) 

Есть мысли?

+0

См. Http://stackoverflow.com/questions/92230/python-beyond-the-basics –

ответ

36

Я собираюсь предположить, что вы исходите из фона 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 "-----------------------------------------------------" 
+4

Ответ дня. Ясный, эффективный, реалистичный. –

5

Конструкторы в Python называются __init__. Вы также должны использовать «я» в качестве первого аргумента для всех методов в вашем классе и использовать это для установки переменных экземпляра в классе.

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) 
+0

printStatus имеет ошибку: он не объявляет себя. – Pramod

+0

Ха! Проклятье! Мы вошли в одно и то же решение. –

+0

Спасибо за вашу помощь, это сработало! Я действительно полагаю, что должен был прочитать учебник перед погружением! –

1

Это недопустимо 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) 
2

Есть целый ряд вещей, указать:

  1. Все методы экземпляра в Python имеют явное чувство собственного аргумента.
  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' 
+0

Можете ли вы сказать, что я программист C# ?! –

1

Ах, эти общие для новых подводных камней разработчиков Python.

Во-первых, конструктор должен называться:

__init__() 

Ваш второй вопрос забывает включить параметр самостоятельного к вашим методам класса.

Кроме того, когда вы определяете второй конструктор, вы заменяете определение метода Computer(). Python чрезвычайно динамичен и с радостью позволит вам переопределить методы класса.

Чем больше pythonic способ, вероятно, использовать значения по умолчанию для параметров, если вы не хотите, чтобы они были необходимы.

4

чувак получить себе книгу питона.Погружение в Python довольно хорошо.

+1

Да, я понимаю это сейчас ... поскольку я не могу получить настоящую книгу хотя бы еще на 16 часов, я думал, что буду погружаться прямо ... ведь «как это сложно?» –

+0

Найдите онлайн-книгу. Вот один из них: http://homepage.mac.com/s_lott/books/python.html –

1

Python не поддерживает перегрузку функции.

Смежные вопросы