2013-08-13 1 views
1

그래서 나는 보통 OOP를 사용하지 않으며 분명히 내가 생각했던 것처럼 그것을 이해하지 못한다. 도시에 대한등록 정보 및 인스턴스에서 상속

class State(object): 
    @property 
    def population(self): 
     return self._population 
    @population.setter 
    def population(self,value): 
     if value < 0: 
      raise ValueError("Population must not be negative") 
     else: 
      self._population = value 

과 (단지 순간)은 거의 동일 클래스 :

는 나는 (지리적) 국가에 대한 클래스가 있다고 가정

class Town(State): 
    @property 
    def population(self): 
     return self._population 
    @population.setter 
    def population(self,value): 
     if value < 0: 
      raise ValueError("Population must not be negative") 
     else: 
      self._population = value 

을 지금은 인스턴스를 가정 특정 인구를 진술하고 제공하십시오. State 인스턴스의 인구를 상속받는 Town 인스턴스를 어떻게 만들 수 있습니까? (일시적으로, 나는 그저 모범이 될 것입니다.) 아니면 상속보다는 구성을 사용해야합니까?

나는 현재 그것을 생각하고 방법이 작동합니다 :

s = State() 

s.population = 10 

t = Town(s) 
--------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-141-00f052d998f0> in <module>() 
----> 1 t = Town(s) 

TypeError: object.__new__() takes no parameters 

답변

3

당신은 마을 국가임을 언급하지 않았다 (싱가포르 나 홍콩에 거주하지 않는 한!). 하지만 주에는 타운이 있다고 말할 수 있습니다. 그것은 구성을 나타냅니다.

상태에는 기본적으로 채우기 특성조차 없습니다. 그래서 국가에서 상속하는 것은 마치 어떤 속성을 제공하지 않습니다

class State(object): 
    @property 
    def population(self): 
     return self._population 
    @population.setter 
    def population(self,value): 
     if value < 0: 
      raise ValueError("Population must not be negative") 
     else: 
      self._population = value 

s = State() 
print s.population 

--output:-- 
raceback (most recent call last): 
    File "1.py", line 13, in <module> 
    print s.population 
    File "1.py", line 4, in population 
    return self._population 
AttributeError: 'State' object has no attribute '_population' 

을 말 그래서 때

지금은 국가의 인스턴스를 가정하고 그것을 특정 인구를 제공합니다. 그 상태를 상속받은 타운 인스턴스를 만들려면 어떻게해야합니까? 인스턴스의 채우기는 무엇입니까?

... Town 클래스는 State 인스턴스를 전혀 알지 못하기 때문에 의미가 없습니다.

class State(object): 
    def __init__(self, name, *towns): 
     self.name = name 
     self.towns = towns 

    @property 
    def population(self): 
     total = 0 
     for town in self.towns: 
      total += town.population 
     return total 

class Town(object): 
    def __init__(self, name, population): 
     self._population = population 

    @property 
    def population(self): 
     return self._population 

    @population.setter 
    def population(self,value): 
     if value < 0: 
      raise ValueError("Population must not be negative") 
     else: 
      self._population = value 

detroit = Town("Detroit", 40) 
lansing = Town("Lansing", 100) 
detroit.population -= 10 
print detroit.population 
print lansing.population 

s = State("Michigan", detroit, lansing) 
print s.population 

--output:-- 
30 
100 
130 
+0

매우 철저한 답변입니다 - 감사합니다! 나는 작곡이 의심되는 상황 이었지만, 당신이 그랬던 것처럼 바닥에서부터 건물의 유용성을 보지 못했습니다. – verbsintransit

1

당신이 쓴 방법 : 구성을 사용

class State(object): 
    @property 
    def population(self): 
     return self._population 
    @population.setter 
    def population(self,value): 
     if value < 0: 
      raise ValueError("Population must not be negative") 
     else: 
      self._population = value 

class Town(object): 
    def __init__(self, population): 
     self._population = population 

    @property 
    def population(self): 
     return self._population 

s = State() 
s.population = 30 
print s.population 

t = Town(s.population) 
print t.population 

,이 같은 일을 할 수있는 : 국가 인스턴스로 타운 인스턴스를 같은 인구를 제공에 대한 분명한 대답은이 작업을 수행하는 것입니다 지금 당장은 타운이 국가라고 말한 반면, 국가는 반드시 타운이 아닙니다. 즉, 도시는 기본적으로 달리 지정되지 않는 한 상태와 똑같이 작동합니다. 당신이 도시 초기화에 상태를 전달하려는 경우

는, 당신은 다음과 같은 기능 뭔가 만들 필요가 : 그 후

class Town(State): 
    def __init__(self, state): 
     self._population = state._population 

을, 당신은 당신의 예에서 TypeError을 얻고, 그것을 안 예상대로 행동 할 것입니다.