2016-12-22 5 views
1

로 정의하기 이처럼 사용이 실행시Set 속성 내가 그 안에 저장된 요소의 유형을 저장하는 속성 <code>type</code>가있는 클래스 <code>Container</code>을 가지고 INT32, 문자열, Float64

array = Container.new(Int32) 
# or 
array = Container.new(String) 

그러나, 내가 얻을 : can't use Class as the type of instance variable @dtype of Crystalla::Ndarray, use a more specific type

어떻게 이것을 달성 할 수 있습니까? 내가 NumPy와 같은 다른 언어와 librairies 보면 , 그들은 그들의 ndarrays의 유형을 저장합니까 : 나는 크리스탈 비슷한 무언가를 달성 할 수있는 방법

np.ndarray(shape=(2,2), dtype=float) 

를?

편집 : DTYPE은 파이썬에서 클래스 자체입니다,하지만 난 당신이 제네릭을 사용한다고 생각

답변

2

을 달성하기 위해 노력하고있어처럼 여전히 타입/클래스를 개최 것으로 보인다. 당신은 항상 클래스 정의에 T 형식을 참조 할 수 있기 때문에 @type 변수 물론 인스턴스의

class Container(T) 
    @type : T.class 
    @array : Array(T) 

    def initialize 
    @array = Array(T).new 
    @type = T 

    puts "Container elements type is #{@type}" 
    end 
end 

array = Container(Int32).new 

제거 할 수 있습니다.