2017-02-22 4 views
0

Q. 어떤 방식으로 Python 기본 클래스에 상수 인수를 전달해야합니까?Python은 기본 클래스에 상수 인수를 전달합니다.

일반적인 예를 사용하면 클래스 CatDog (모두 Animal에서 파생 됨)이 있습니다. 을 호출하면 적절한 단어 ("meow", "woof")가 반환됩니다.

내 문제는 클래스의 모든 인스턴스가 같은 소리를, 따라서 나는 soundAnimal에 전달할 수있는 동안이다 : 이것은 우리가 모든 경우에 "woof"를 저장하기 때문에, 낭비 보인다

class Animal: 
    def __init__(sound): 
     self.sound = sound 

class Dog: 
    def __init__(): 
     super().__init__("woof") 

내가 가진 백만 개의 개와 10 억 개의 고양이. 내가 대신 다음 방법을 사용할 수 있습니다

class Animal: 
    @staticmethod 
    def sound(): 
     raise NotImplementedError("Abstract") 

class Dog: 
    @staticmethod 
    def sound(): 
     return "woof" 

그러나이 지금 내 동물은 모두 매우 조용하기 때문에, 이것은 쉽게 놓친 다른 사람이 나타나서 내 공들여 작성한 문서를 읽는하지 않고 Bird 클래스를 기록, 만 발견 할 때 그들은 메서드가 실제로 호출되었을 때 블루 문에서 메서드를 한 번 잊어 버렸습니다.

이상적으로 나는 Animal 클래스 자체가 매개 변수를 사용하는 C++ 템플릿과 같은 것을 원합니다. 즉각적인 오류가 발생하지 않고 놓칠 수 없으며 인스턴스 당 더 이상의 공간을 차지하지 않습니다.

template<sound> 
class Animal() 
    . . . 

파이썬에서 내가 한 일을 성취하는 방법이 있습니까?

+0

모든 개 인스턴스는 문자열 인턴하기 때문에 동일한 실제 문자열 객체를 받아야한다고 생각합니다. –

+0

잘 모르겠습니다 만,이 경우에는 '__slots__'가 필요합니다. – vks

+0

@PaulRooney는 여전히 모든 객체에 대한 포인터를 가지고 있습니다. 또한, interned 문자열에 대한 포인터는 "woof"문자열 자체보다 긴 64 비트 시스템에서 8 바이트가됩니다. –

답변

0

공장 디자인 패턴을 사용해 볼 수 있습니다. 이런 식으로 뭔가 :

class AnimalFactory(object): 
    animals={} 

    @staticmethod 
    def registerAnimal(animalName, animalClass): 
     if not hasattr(animalClass, "sound"): 
      raise Exception("All animals need to make a sound") 
     AnimalFactory.animals[animalName]=animalClass 

    @staticmethod 
    def createNewAnimal(animalName): 
     return AnimalFactory.animals[animalName]() 

class Dog: 
    sound="woof" 

AnimalFactory.registerAnimal("dog", Dog) 

dog1=AnimalFactory.createNewAnimal("dog") 
print dog1.sound 

class Cat: 
    pass 

AnimalFactory.registerAnimal("cat", Cat) 

위의 코드가 생성하는 다음과 같은 출력 물론

woof 
Traceback (most recent call last): 
    File "animals.py", line 25, in <module> 
    AnimalFactory.registerAnimal("cat", Cat) 
    File "animals.py", line 7, in registerAnimal 
    raise Exception("All animals need to make a sound") 

는, 사용자는 클래스를 등록하는 것을 잊지 수 있지만 한 다른 사용자가 AnimalFactory을 사용하는 등 새로운 동물을 만들 수 , 이것은 잘 작동합니다.