2016-11-27 1 views
1

저는 Python을 처음 접했고 이진 파일에서 읽고 쓰는 코드를 작성했습니다.Python 클래스 "Main"값

파일에 포함될 모든 유형의 데이터에 대한 클래스를 만들고이를 유지하기 위해 InteriorIO라고하는 모든 클래스에서 상속받을 클래스를 하나 만들었습니다. 나는 각 클래스가 파일을 읽거나 파일로부터 데이터를 읽고 쓰는 읽기 및 쓰기 메소드를 갖기를 원한다. 그러나 InteriorIO를 상속하는 동시에 str 또는 int와 같이 동작하여 값을 반환하므로 __str__ 또는 __int__을 가장 유사하게 수정합니다.

class InteriorIO(object): 
    __metaclass__ = ABCMeta 

    @abstractmethod 
    def read(this, f): 
     pass 

    @abstractmethod 
    def write(this, f): 
     pass 

class byteIO(InteriorIO): 
    def __init__(this, value=None): 
     this.value = value 

    def read(this, f): 
     this.value = struct.unpack("B", f.read(1))[0] 

    def __str__: 
     return value; 

class U16IO(InteriorIO): 
    def __init__(this, value=None): 
     this.value = value 

    def read(this, f): 
     this.value = struct.unpack("<H", f.read(2))[0] 

    def __int__: 
     return value; 

# how I'd like it to work 
f.open("C:/some/path/file.bin") 
# In the file, the fileVersion is a U16 
fileVersion = U16IO() 
# We read the value from the file, storing it in fileVersion 
fileVersion.read(f) 
# writes the fileVersion that was just read from the file 
print(str(fileVersion)) 
# now let's say we want to write the number 35 to the file in the form of a U16, so we store the value 35 in valueToWrite 
valueToWrite = U16IO(35) 
# prints the value 35 
print(valueToWrite) 
# writes the number 35 to the file 
valueToWrite.write(f) 
f.close() 

하단의 코드는 작동하지만 클래스가 잘못 이해되고 너무 모호합니다. 나는 임의의 이름 인 this.value을 "모든"객체의 "주"값으로 설정 한 다음 그 값을 원하는 유형으로 반환하고 있습니다.

클래스를 모두 정리하여 InteriorIO에서 상속받는 가장 깨끗한 방법은 무엇입니까? 그렇지만 값을 반환한다는 점에서 str이나 int처럼 작동합니까?

답변

1

이 경우 Factory Design Pattern을 고려해 볼 수 있습니다. ","생성 "을 반대하는 따라서 제목을 결정합니다

class Cup: 
    color = "" 

    # This is the factory method 
    @staticmethod 
    def getCup(cupColor, value): 
     if (cupColor == "red"): 
      return RedCup(value) 
     elif (cupColor == "blue"): 
      return BlueCup(value) 
     else: 
      return None 

class RedCup(Cup): 
    color = "Red" 

    def __init__(self, value): 
     self.value = value 


class BlueCup(Cup): 
    color = "Blue" 

    def __init__(self, value): 
     self.value = value 

# A little testing 
redCup = Cup.getCup("red", 10) 
print("{} ({})".format(redCup.color, redCup.__class__.__name__)) 

blueCup = Cup.getCup("blue", 20) 
print("{} ({})".format(blueCup.color, blueCup.__class__.__name__)) 

그래서 당신이 값을 주어진 정적 메서드 getCup를 포함하는 공장 Cup이 : 여기

는 아이디어를 설명하는 간단한 예입니다 공장".

그런 다음 코드에서 공장의 getCup 메서드를 호출하기 만하면 작업 할 적절한 클래스가 반환됩니다.

그들은 __int____str__을 처리 할 방법 중 하나가없는 클래스에서 생각하고 구현하고 다시 돌아 오지 않습니다. 따라서 U16IO는 __str__ 메서드를 구현하여 None을 반환하고 byteIO는 __int__을 구현해야하며 None을 반환해야합니다.

+0

내가 이미 알고있는 값을 쓰기 위해 U16IO에서했던 것처럼 RedCup/BlueCup에 어떤 가치를 전달할 수 있습니까? – tomysshadow

+1

@tomysshadow'RedCup'과'BlueCup'은 여전히 ​​매개 변수를 받아 들일 수있는 생성자 (예 :'__init__')를 가질 수 있습니다. 팩토리 메서드에 전달 된 값이 클래스를 만들지 결정할 수 있습니까? 위의 예 (추가 한 참조에서 가져온 것)는 최소한의 것으로, 생성자와 매개 변수를 전달할 수 없다는 것을 의미하지는 않습니다. – Rafael

+0

생성자가있는 대/소문자를 포함하도록 답변을 업데이트했습니다. 그것으로 전달됩니다. – Rafael

1

왜 여기서 수업을 사용합니까? 지나치게 복잡해 보입니다.

readwrite의 두 가지 기능을 정의 할 수 있습니다.

def bread(format, binaryfile): 
    return struct.unpack(format, binaryfile.read(format.calcsize())) 

def bwrite(format, binaryfile, *args): 
    binaryfile.write(struct.pack(format, *args)) 
+0

나는 하나의 클래스 대신에 2 개 또는 3 개의 값을 취하는보다 복잡한 클래스가 있기 때문입니다. – tomysshadow

+0

@tomysshadow'bread' 함수는 이미 유스 케이스를 처리해야합니다. 나는 그것을 처리하기 위해'bwrite'도 변경했습니다. –