2013-07-23 57 views
-6

運行Python類和對象錯誤

Enter the length of the rectangle: 4 
Enter the width of the rectangle: 2 
Traceback (most recent call last): 
    File "C:\Users\Shourav\Desktop\rectangle_startfile.py", line 50, in <module> 
    main() 
    File "C:\Users\Shourav\Desktop\rectangle_startfile.py", line 34, in main 
    my_rect = Rectangle() 
TypeError: __init__() missing 2 required positional arguments: 'length' and 'width' 

代碼程序,而我得到的錯誤:

# class definition 

class Rectangle: 

    def __init__(self, length, width): 

     self.__length = length 
     self.__width = width 
     self.__area = area 

    def set_length(self, length): 
     self.__length = length 

    def set_width(self, width): 
     self.__width = width 

    def get_length(self, length): 
     return self.__length 

    def get_width(self, width): 
     return self.__width 

    def get_area(self, length, width): 
     area = (length * width) 
     self.__area = area 
     return self.__area 


# main function 
def main(): 

    length = int(input("Enter the length of the rectangle: ")) 
    width = int(input("Enter the width of the rectangle: ")) 

    my_rect = Rectangle() 

    my_rect.set_length(length) 
    my_rect.set_width(width) 

    print('The length is',my_rect.get_length()) 
    print('The width is', my_rect.get_width()) 

    print('The area is',my_rect.get_area()) 
    print(my_rect) 

    input('press enter to continue') 


# Call the main function 

main() 
+0

您好,我我是一名Python編程初學者。這是我對象和類的第一個程序在訪問類文件時遇到問題 – user2607610

回答

3

你定義一個Rectangle類,它的初始化方法需要兩個參數:

class Rectangle: 
    def __init__(self, length, width): 

尚未嘗試創建一個而沒有通過克這些參數:

my_rect = Rectangle() 

通在長度和寬度,而不是:

my_rect = Rectangle(length, width) 

你的下一個問題是:area沒有定義,你可能要計算的是:

class Rectangle: 
    def __init__(self, length, width): 
     self.__length = length 
     self.__width = width 
     self.get_area(length, width) 

在設計說明中:通常在Python中,您不使用像這樣的「私有」變量;只需使用普通的屬性來代替:

class Rectangle: 
    def __init__(self, length, width): 
        self.length = length 
        self.width = width 

    @property 
    def area(self): 
     return self.length * self.width 

直接獲取或根據需要設置的實例的屬性:

print('The length is', my_rect.length) 
print('The width is', my_rect.width) 
print('The area is', my_rect.area) 

屬性以雙下劃線(__name)開始是爲了避免子從意外重新定義它們;目的是保護這些屬性不被破壞,因爲它們對當前課堂的內部工作至關重要。事實上,他們的名字受到損壞,因此不易訪問並不能真正使他們變得私密,只是難以達到。無論你做什麼,例如,不要將它們誤認爲私有名稱,就像在Java中那樣。

0

當你聲明my_rect = Rectangle()它需要lengthwidth被傳遞給它,如Rectangle __init__方法所述。

0

Rectangle的構造函數需要兩個你沒有設置的參數。

參見:

class Rectangle: 

    def __init__(self, length, width): 

my_rect = Rectangle() 

您需要:

my_rect = Rectangle(length, width) 

只是爲了您的信息:

在構造函數中自我參數是一個參數,它將通過隱含地編輯,所以你不要傳遞它(至少不是通過在代碼中實現它)。

0

您已在Rectangle類中定義__init__的方式需要你有一個長度和寬度稱之爲:

def __init__(self, length, width): 

變化

my_rect = Rectangle() 

my_rect.set_length(length) 
my_rect.set_width(width) 

my_rect = Rectangle(length, width)