저는 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처럼 작동합니까?
내가 이미 알고있는 값을 쓰기 위해 U16IO에서했던 것처럼 RedCup/BlueCup에 어떤 가치를 전달할 수 있습니까? – tomysshadow
@tomysshadow'RedCup'과'BlueCup'은 여전히 매개 변수를 받아 들일 수있는 생성자 (예 :'__init__')를 가질 수 있습니다. 팩토리 메서드에 전달 된 값이 클래스를 만들지 결정할 수 있습니까? 위의 예 (추가 한 참조에서 가져온 것)는 최소한의 것으로, 생성자와 매개 변수를 전달할 수 없다는 것을 의미하지는 않습니다. – Rafael
생성자가있는 대/소문자를 포함하도록 답변을 업데이트했습니다. 그것으로 전달됩니다. – Rafael