2013-12-11 3 views
1

나는 사용자가 특정 속성을 가진 새 차량을 만들 수있는 프로그램을 만들었습니다. 이제 각 차량을 모든 차량 목록에 추가 한 다음 표시하는 인벤토리 기능을 만들어야합니다. 이것은 내가 가진 것이지만 작동하지 않습니다. 인벤토리 기능을 좀 더 자세히 살펴볼 필요가 있습니까?Python 클래스 만들기 객체 목록

class Inventory: 

    def __init__(self, list1 = []): 
     self.list1 = list1[:] 
    def addVehicle(self, vehicle): 
     self.list1.append(vehicle) 
    def Display(self): 
     print(self.list1) 
+3

파이썬 이전에 다른 객체 지향 언어, 즉 게터와 세터가 권장 된 연습을 배웠습니까? – DSM

+2

어떻게 작동하지 않습니까? 흔적? 잘못된 출력입니까? –

+0

주 프로그램을 실행할 때 출력되는 유일한 것은'[]'이며 추가 된 모든 차량 목록이 아닙니다. – user3014014

답변

2

어딘가 당신이 호출 할 필요가 inventory.addVehicle (난 당신의 코드에서 놓친하지 않는 한), 실제로 인벤토리에 최근에 생성 된 개체를 추가하기 위해서이다.

또 다른 문제는 main을 반복적으로 호출하고 main의 맨 위에 inventory을 덮어 쓰는 것입니다. 우리는 모두 (이중 밑줄을 생략하고 작성하고 직접 읽기 : 당신은 모든 getter 및 setter가 필요하지 않습니다 : 보조 노트에

def main(): 
    inventory = Inventory() 

    while True: 
     classType = input('Is the vehicle a car, truck, or suv? ') 
     vehicle = None 
     if classType == 'car': 
      #inputs 
      vehicle = Car(make, model, year, mileage, price, doors) 
     elif classType == 'truck': 
      #inputs 
      vehicle = Truck(make, model, year, mileage, price, drive) 
     elif classType == 'suv': 
      #inputs 
      vehicle = SUV(make, model, year, mileage, price, passengers) 
     else: print('Unkown vehicle type') 
     if vehicle: inventory.addVehicle (vehicle) 
     cont = input('Would you like to add another vehicle? */n ') 
     if cont == 'n': break 
    inventory.Display() 

을 :

아마 당신은이처럼 리팩토링 수 있습니다 어른들은 여기에). 캡슐화가 정말로 중요하다면 @property@setter 데코레이터를 사용할 수 있습니다.

1

난 당신이 다음과 같은 코드가 일을 단축해야한다고 생각 당신이 사용할 수있는 것 같습니다

class Vehicle: 
    def __init__(self, make, model, year, mileage, price): 
     self.__make = make 
     self.__model = model 
     self.__year = year 
     self.__mileage = mileage 
     self.__price = price 

    def iMake(self, make): 
     self.__make = make 

    def iModel(self, model): 
     self.__model = model 

    def iYear(self, year): 
     self.__year = year 

    def iMileage(self, mileage): 
     self.__mileage = mileage 

    def iPrice(self, price): 
     self.__price = price 

    def getMake(self): 
     return self.__make 

    def getModel(self): 
     return self.__model 

    def getYear(self): 
     return self.__year 

    def getMileage(self): 
     return self.__mileage 

    def getPrice(self): 
     return self.__price 

    def Display_Vehicle(self): 
     print('Inventory unit: %s' % self.__class__.name) 
     print('Make: ' , self.__make) 
     print('Model: ', self.__model) 
     print('Year: ' , self.__year) 
     print('Miles: ', self.__mileage) 
     print('Price: ', self.__price) 

class Car(Vehicle): 
    name = 'Car' 
    def __init__(self,make, model, year, mileage, price, x): 
     Vehicle.__init__(self,make, model, year, mileage, price) 
     self.__doors = x 
    def iDoors(self, doors): 
     self.__doors = doors 
    def getDoors(self): 
     return self.__doors 
    def Display(self): 
     self.Display_Vehicle() 
     print('Number of doors: ', self.__doors) 

class Truck(Vehicle): 
    name = 'Truck' 
    def __init__(self,make, model, year, mileage, price, x): 
     Vehicle.__init__(self,make, model, year, mileage, price) 
     self.__drive = x 
    def iDrive(self, drive): 
     self.__drive = drive 
    def getDrive(self): 
     return self.__drive 
    def Display(self): 
     self.Display_Vehicle() 
     print('Drive type: ', self.__drive) 

class SUV(Vehicle): 
    name = 'SUV' 
    def __init__(self,make, model, year, mileage, price, x): 
     Vehicle.__init__(self,make, model, year, mileage, price) 
     self.__passengers = x 
    def iCapacity(self, passengers): 
     self.__passengers = passengers 
    def getCapacity(self): 
     return self.__passengers 
    def Display(self): 
     self.Display_Vehicle() 
     print('Number of passengers: ', self.__passengers) 

def main(): 
    inventory = [] 
    while True: 
     classType = input('Is the vehicle a car, truck, or suv? ') 
     print (classType) 
     make = input('Please enter the make of the %s: ' % classType) 
     model = input('Please enter the model of the %s: ' % classType) 
     year = input('Please enter the year of the %s: ' % classType) 
     mileage = input('Please enter the mileage of the %s: ' % classType) 
     price = input('Please enter the price of the %s: ' % classType) 
     if classType == 'car':   
      x = input('Please enter the amount of doors on the car: ') 
      inventory.append(Car(make, model, year, mileage, price, x)) 
     elif classType == 'truck': 
      x = input('Please enter 2 wheel or 4 wheel drive for the truck: ') 
      inventory.append(Truck(make, model, year, mileage, price, x)) 
     elif classType == 'suv': 
      x = input('Please enter the capacity of the suv: ') 
      inventory.append(SUV(make, model, year, mileage, price, x)) 
     print('\n\n') 
     inventory[-1].Display() 
     cont = 'go' 
     while cont not in ('y','n'): 
      cont = input('Would you like to add another vehicle? y/n ') 
     if cont == 'n': 
      print(inventory) 
      break 

if __name__ == '__main__': 
    main() 
+0

이것은 OOP에 반대되는 약간의 반 패턴입니다. 각 객체에 유형이있는 경우 왜 type이라는 속성을 부여해야합니까? IMHO, 정말 좋은 연습. – Hyperboreus

+0

@Hyperboreus 인수가 승인되었습니다. 코드를 변경했습니다. 내 생각은 반복의 코드를 단축하는 것이지만 너무 멀리 갔다. – eyquem

0

(나는 그것을 볼 수 inventory 클래스의 인스턴스를 만들기 위해 지금까지 절대적으로 필요가 없습니다) 클래스 변수. 당신이 당신의 차량을 인쇄하려면

all_vehicles = [] 

def __init__(self, whatever): 
    # Your code 
    # … 
    # and now you just add the vehicle to the list of all vehicles. 
    # stored in a class variable 
    Vehicle.all_vehicles.append(self) 

, 당신은 단지

print Vehicle.all_vehicles 

하지만이 단지에 있습니다

클래스 차량 : 난 당신이 Vehicle - 클래스에 몇 가지 작은 코드를 추가 제안 모든 하위 클래스에서 Vehicle의 메소드 __init__ (괜찮은 코드로 작성되어야 함)을 호출하면 작동합니다.