필자가 본 내장 클래스와 다른 "성숙한"파이썬 구성 요소처럼 작동하는 클래스를 작성하려고합니다. 나의 Pythonic 교육은 학급별로 조금 여드름이 많다. 나는 그것이 모두 섞여서 걱정된다.모듈 구성, 상속 및 @classmethods
처리되지 않은 파일 (및 해당 이름) 사전과 처리 된 파일 (및 해당 이름) 사전을 포함하는 일종의 저장소 역할을하는 클래스를 만들고 싶습니다. 파일을 열고 처리하는 것과 같은 일을 처리하는 다른 하위 클래스를 구현하고 싶습니다. 파일 처리 클래스는 기본 클래스의 사전을 업데이트 할 수 있어야합니다. 내가 직접 개별적으로 예를 들어 모든 것을 인스턴스화 할 필요없이 다양한 서브 모듈을 호출 할 수 싶습니다
import Pythia
p = Pythia()
p.FileManager.addFile("/path/to/some/file")
또는
Pythia.FileManager.addFile("/path/to/some/file")
내가 물건에 주위를 찾고 있었어요 약 @classmethod
및 super
등이 있지만 전적으로 그것을 이해한다고 말할 수는 없습니다. 저는 또한 제가 상속의 전적인 사슬을 가지고 있을지도 모른다고 의심하기 시작했습니다. 제가 생각하기에 제 메인 클래스는 실제로 처리 클래스의 하위 클래스 여야합니다. 또한이 모든 것이 패키지로 더 잘 작동하는지 궁금하지만, 이는 별개의, 매우 협박적인 문제입니다.
여기 내 코드는 지금까지의 :
#!/usr/bin/python
import re
import os
class Pythia(object):
def __init__(self):
self.raw_files = {}
self.parsed_files = {}
self.FileManger = FileManager()
def listf(self,fname,f):
if fname in self.raw_files.keys():
_isRaw = "raw"
elif fname in self.parsed_files.keys():
_isRaw = "parsed"
else:
return "Error: invalid file"
print "{} ({}):{}...".format(fname,_isRaw,f[:100])
def listRaw(self,n=None):
max = n or len(self.raw_files.items())
for item in self.raw_files.items()[:max]:
listf(item[0],item[1])
def listParsed(self,n=None):
max = n or len(self.parsed_files.items())
for item in self.parsed_files.items()[:max]:
listf(item[0],item[1])
class FileManager(Pythia):
def __init__(self):
pass
def addFile(self,f,name=None,recurse=True,*args):
if name:
fname = name
else:
fname = ".".join(os.path.basename(f).split(".")[:-1])
if os.path.exists(f):
if not os.path.isdir(f):
with open(f) as fil:
Pythia.raw_files[fname] = fil.read()
else:
print "{} seems to be a directory.".format(f)
if recurse == False:
return "Stopping..."
elif recurse == True:
print "Recursively navingating directory {}".format(f)
addFiles(dir,*args)
else:
recurse = raw_input("Recursively navigate through directory {}? (Y/n)".format(f))
if recurse[0].lower() == "n":
return "Stopping..."
else:
addFiles(dir,*args)
else:
print "Error: file or directory not found at {}".format(f)
def addFiles(self,directory=None,*args):
if directory:
self._recursivelyOpen(directory)
def argHandler(arg):
if isinstance(arg,str):
self._recursivelyOpen(arg)
elif isinstance(arg,tuple):
self.addFile(arg[0],arg[1])
else:
print "Warning: {} is not a valid argument...skipping..."
pass
for arg in args:
if not isinstance(arg,(str,dict)):
if len(arg) > 2:
for subArg in arg:
argHandler(subArg)
else:
argHandler(arg)
elif isinstance(arg,dict):
for item in arg.items():
argHandler(item)
else:
argHandler(arg)
def _recursivelyOpen(self,f):
if os.path.isdir(f):
l = [os.path.join(f,x) for x in os.listdir(f) if x[0] != "."]
for x in l:
_recursivelyOpen(x)
else:
addFile(f)
'Pythia 가져 오기'는 모듈이 아닌 클래스입니다. 그래서 당신은'피티 아 (Pythia)'를 할 수 없습니다. Pythia라는 이름의 모듈에서 Pythia라는 클래스를 가질 수 있습니다.이 경우 Pythia.Pythia()를 할 수 있습니다. 그러나 모듈을 pythia라고 부름으로써 혼란을 피하는 것이 더 낫습니다 (PEP8이 암시 하듯이). – abarnert
한 가지 더 :'self.FileManger = FileManager()'는 정말 나쁜 생각입니다. 그 클래스의 클래스와 인스턴스의 이름을 지정하면 똑같은 것이 혼란을 가져올 수 있습니다. (Eevee가 제안한대로 PEP8을 따르는 경우, 결코'file_manager'는 일반적인'FileManager' 인스턴스에 대한 합리적인 이름입니다. 그러나 그렇지 않다면, Apple과 같은 이름을 짓기위한 다른 스타일이 필요합니다. 스타일'aFileManager'). – abarnert