2008-11-23 14 views
7

CẢNH BÁO: Tôi đã học Python trong tất cả 10 phút để xin lỗi vì bất kỳ câu hỏi ngu ngốc nào!Python: Sự cố với các nhà xây dựng quá tải

Tôi đã viết đoạn code sau, tuy nhiên tôi nhận được ngoại lệ sau đây:

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) 

Bất kỳ suy nghĩ?

+0

Xem http://stackoverflow.com/questions/92230/python-beyond-the-basics –

Trả lời

36

Tôi sẽ giả sử bạn đang đến từ nền Java-ish, do đó, có một số khác biệt chính để chỉ ra.

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

Câu trả lời trong ngày. Rõ ràng, hiệu quả, thực tế. –

5

Các nhà xây dựng bằng Python được gọi là __init__. Bạn cũng phải sử dụng "self" làm đối số đầu tiên cho tất cả các phương thức trong lớp của bạn, và sử dụng nó để đặt các biến cá thể trong lớp.

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 có lỗi: nó không tự khai báo. – Pramod

+0

Ha! Jinx! Chúng tôi đã nhập cùng một giải pháp. –

+0

Cảm ơn sự giúp đỡ của bạn, nó đã làm việc một điều trị! Tôi thực sự cho rằng tôi nên đọc một hướng dẫn trước khi lặn! –

1

Đó không phải là trăn hợp lệ.

Phương thức khởi tạo cho lớp Python là def __init__(self, ...): và bạn không thể quá tải nó.

Việc bạn có thể làm là sử dụng các giá trị mặc định cho các đối số, ví dụ:

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

Có một số điều cần chỉ ra:

  1. Tất cả các phương pháp dụ bằng Python có một tự lập luận rõ ràng.
  2. Các nhà xây dựng được gọi là __init__.
  3. Bạn không thể quá tải phương pháp. Bạn có thể đạt được hiệu ứng tương tự bằng cách sử dụng đối số phương thức mặc định.

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

Bạn có thể nói rằng tôi là một lập trình viên C# ?! –

1

Ah, đây là những vấn đề thường cho các nhà phát triển python mới.

Thứ nhất, các nhà xây dựng nên được gọi là:

__init__() 

Vấn đề thứ hai của bạn là quên bao gồm tự tham số để phương pháp lớp học của bạn.

Hơn nữa, khi bạn xác định hàm tạo thứ hai, bạn đang thay thế định nghĩa của phương thức Computer(). Python cực kỳ năng động và sẽ vui vẻ cho phép bạn xác định lại các phương thức lớp.

Cách có chiều sâu hơn có lẽ là sử dụng các giá trị mặc định cho các tham số nếu bạn không muốn yêu cầu chúng.

4

dude tự lấy cho mình một cuốn sách python.Nhảy vào Python khá tốt.

+1

Vâng, tôi nhận ra điều này ngay bây giờ ... vì tôi không thể có được một cuốn sách thực sự trong ít nhất 16 giờ nữa, tôi nghĩ rằng tôi sẽ lặn ngay ... sau tất cả "khó khăn như thế nào ?!" –

+0

Tìm một cuốn sách trực tuyến. Đây là một: http://homepage.mac.com/s_lott/books/python.html –

1

Python không hỗ trợ quá tải chức năng.