2015-02-03 3 views
-1

클래스 Vehicle을 정의해야합니다. 클래스의 각 객체에는 license (번호판)과 year (작성 연도)의 두 속성과 이러한 속성을 반환하는 두 가지 속성이 있습니다.파이썬에서 클래스를 이해하고 있습니까?

은 또한, 나는 후자의 두 가지를 알 수있는 방법 두 이상의 속성, dis (변위)와 max (차에있는 사람들의 최대 수)가 클래스 Car, Vehicle의 파생 클래스를 정의해야 . 내가 파이썬에서 클래스와 몇 가지 문제가

class vehicle: 
    def __init__(self,License_plate,Year): 
    self.license = License_plate 
    self.year = Year 
    def year(self): 
    return self.year 
    def license(self): 
    return self.license 

class car(vehicle): 
    def __init__(self,License_plate,Year,Displacement,maximum): 
    veicolo.__init__(self, License_plate, Year) 
    self.dis = Displacement 
    self.max = maximum 
    def displacement(self): 
    return self.dis 
    def max(self): 
    return self.max 



a = vehicle('ASDFE',1234)    #This is how I tried to run it 
a.year()        #Here I got an ERROR : 
a.license()       #TypeError: 'int' object is not callable 
b = car('ASDERTWWW',1234,7000,2340) 
b.displacement() 
b.max() 

:

내가 작성하는 노력 코드입니다. 나는 파생 된 클래스의 사용을 이해할 수 없다.

+0

속성 및 메소드에 동일한 이름을 사용하고 있습니다. 이것은 매우 나쁜 생각입니다. 사실, 당신은 전혀 방법을 필요로하지 않습니다. 직접 속성에 액세스 할 수 있습니다 (또는 '@ 속성'사용 - 예 : http://stackoverflow.com/q/6618002/3001761 참조). – jonrsharpe

+0

http://www.memonic.com/user/pneff/folder/development/id/1ttgT – Jasper

+0

예! 나는 내 문제를 이해했다! 고마워요 :) –

답변

1

파이썬에서는 getters와 setter가 필요하지 않습니다.

class Vehicle(object): 
    def __init__(self, year): 
     self.year = year 

class Car(Vehicle): 
    def __init__(self, name, year): 
     super(Car, self).__init__(year) 
     self.name = name 

a = Vehicle(1995) 
print a.year 
b = Car("test", 1992) 
print b.name 
print b.year 
0

같은 이름의 메소드와 변수가 있습니다. a.year()으로 전화 할 때 year 변수를 호출하려고합니다.

하나의 솔루션은 _year 또는 getYear의 변수 중 하나의 이름을 바꾸는 것입니다. 또는 변수에 직접 액세스 할 수도 있습니다. >>> a.year ->1234

관련 문제