2008-11-23 3 views
7

경고 : 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-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 "-----------------------------------------------------" 
+4

오늘의 답. 명확하고, 효율적이며, 현실적입니다. –

5

파이썬의 생성자는 __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) 
+0

printStatus에는 버그가 있습니다. 자체를 선언하지 않습니다. – Pramod

+0

하! 재수 없는 물건! 우리는 같은 해결책을 입력했습니다. –

+0

도움을 주셔서 감사합니다. 나는 정말로 내가 잠수 전에 자습서를 읽어야했다라고 생각한다! –

1

유효하지 않은 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

처음에는 here으로 보입니다.

2

은 여러 가지가 지적하고 있습니다 파이썬에서

  1. 모든 인스턴스 메소드가 명시 적 자기 주장이있다.
  2. 생성자는 __init__입니다.
  3. 메서드를 오버로드 할 수 없습니다. 기본 메소드 인수를 사용하여 유사한 효과를 얻을 수 있습니다.

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

내가 C# 프로그래머라고 말할 수 있니?! –

1

아,이 새로운 파이썬 개발자를위한 일반적인 개는됩니다.

먼저, 생성자를 호출해야합니다

__init__() 

두 번째 문제는 수업 방법과 자기 매개 변수를 포함 잊고있다.

두 번째 생성자를 정의하면 Computer() 메서드의 정의가 바뀝니다. 파이썬은 극도로 역동적이며 유쾌하게 클래스 메소드를 다시 정의 할 수 있습니다.

매개 변수를 필요로하지 않으려면 매개 변수의 기본값을 사용하는 것이 좋습니다.

4

제 자신이 파이썬 책을 갖습니다.파이썬으로 들어가는 것은 꽤 좋습니다.

+1

그래, 지금이 사실을 깨달았 어. 적어도 16 시간 동안 실제 책을 구할 수 없기 때문에, 나는 잠수함에 빠져 들었다고 생각했다. 결국 "얼마나 어려울 수 있니?" –

+0

온라인 서적을 찾으십시오. 여기에 하나 : http://homepage.mac.com/s_lott/books/python.html –

1

파이썬은 함수 오버로딩을 지원하지 않습니다.

관련 문제