|
|||||||
|
|
|
![]() |
|
|
Strumenti |
|
|
#1 |
|
Member
Iscritto dal: Mar 2011
Messaggi: 125
|
[Python] Dividere il sorgente in più file
salve, stavo cercando di dividere il codice che sto scrivendo in più file, ma al momento senza successo
Sostanzialmente ho spostato tutte le funzioni in un file di nome basePPT, all'interno della classe basePPT. Poi, nel file contenente il codice in cui voglio utilizzare le funzioni, ho scritto Codice:
from basePPT import basePPT |
|
|
|
|
|
#2 |
|
Senior Member
Iscritto dal: Mar 2007
Città: Milano Beach
Messaggi: 1696
|
basePPT.py e il file in cui utilizzi la classe sono nella stessa directory?
Posta un po' di codice, il ragionamento è corretto ma c'è qualcosa di sbagliato nell'implementazione
__________________
~ Cthulhu: MacBookPro 13.3" ~ Azathoth: D510MO |
|
|
|
|
|
#3 |
|
Member
Iscritto dal: Mar 2011
Messaggi: 125
|
Si sono nella stessa directory.
Questo è parte il codice che utilizza la classe: Codice:
import sys, pygame, random
from pygame.locals import *
from basePPT import basePPT
def main():
global FPSCLOCK, DISPLAYSURF, BASICFONT, CHORD
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
FPSCLOCK = pygame.time.Clock()
BASICFONT = pygame.font.Font('freesansbold.ttf', 20)
pygame.display.set_caption('Perfect Pitch Trainer')
lastNote = None # to track the last played note
lesson_Button = pygame.Rect(30, 30, 30, 30) # to start the lesson mode
instructions_Button = pygame.Rect(30, 70, 30, 30) # to show the game instructions
voidStr_Button = pygame.Rect(30, 110, 30, 30) # to generate guitar void strings
mute_Button = pygame.Rect(30, 150, 30, 30) # to stop all the active sounds
while True: # main game loop
# set the display
DISPLAYSURF.fill(BGCOLOR)
generateFretBoard()
makeButton('Lessons', lesson_Button, DARKGREEN)
makeButton('Sound Stop', mute_Button, DARKGREEN)
makeButton('Guitar Void String', voidStr_Button, DARKGREEN)
makeButton('Instructions', instructions_Button, DARKGREEN)
showLastNotes(LASTNOTELIST)
checkForQuit()
for event in pygame.event.get():
# check if the player is doing a chord
if event.type == KEYDOWN:
if event.key == K_c:
CHORD = True
if event.type == KEYUP:
if event.key == K_c:
CHORD = False
# check what the mouse is clicking
if event.type == MOUSEBUTTONUP:
mousex, mousey = event.pos
for OCTAVE in OCTAVELIST:
checkPressedFret((mousex, mousey), OCTAVE)
for OCTAVE in sOCTAVELIST:
checkPressedFretS((mousex, mousey), OCTAVE)
mousePos((mousex, mousey))
FPSCLOCK.tick()
pygame.display.update()
Codice:
class basePPT: def showLastNotes(lastNoteList): toplefty = 190 for note in lastNoteList: lastNoteText = BASICFONT.render(note, True, GOLD, BGCOLOR) lastNoteRect = lastNoteText.get_rect() lastNoteRect.topleft = (30, toplefty) toplefty += 30 DISPLAYSURF.blit(lastNoteText, lastNoteRect) def makeButton(text, Rect, color): # used to generate the function's button pygame.draw.rect(DISPLAYSURF, BLACK, Rect) pygame.draw.rect(DISPLAYSURF, DARKGREEN, Rect, 1) textSurf = BASICFONT.render(text, True, RED, BGCOLOR) textRect = textSurf.get_rect() textRect.topleft = Rect.topright DISPLAYSURF.blit(textSurf, textRect) def mousePos((mousex, mousey)): # generate a red spot to show better what the mouse is clicking pygame.draw.circle(DISPLAYSURF, RED, (mousex, mousey), 10) pygame.display.update() pygame.time.wait(100) def lastNotePatcher(lastNote): # patch the LASTNOTELIST, which contains the last 3 notes global LASTNOTELIST, FIRSTCHORDNOTE if CHORD == True: if FIRSTCHORDNOTE == False: LASTNOTELIST = [lastNote] + LASTNOTELIST FIRSTCHORDNOTE = True elif FIRSTCHORDNOTE == True: LASTNOTELIST[0] += " " + lastNote else: LASTNOTELIST = [lastNote] + LASTNOTELIST FIRSTCHORDNOTE = False if len(LASTNOTELIST) == 4: del LASTNOTELIST[3] def generateFretBoard(): # generate the fretboard drawWood() generateWhiteFrets(WHITESTARTCOORDX, OCTAVE1) generateWhiteFrets(WHITESTARTCOORDX + OCTAVELENGHT, OCTAVE2) generateWhiteFrets(WHITESTARTCOORDX + (OCTAVELENGHT * 2), OCTAVE3) generateWhiteFrets(WHITESTARTCOORDX + (OCTAVELENGHT * 3), OCTAVE4) generateBlackFrets(BLACKSTARTCOORDX, OCTAVE1S) generateBlackFrets(BLACKSTARTCOORDX + OCTAVELENGHT, OCTAVE2S) generateBlackFrets(BLACKSTARTCOORDX + (OCTAVELENGHT * 2), OCTAVE3S) generateBlackFrets(BLACKSTARTCOORDX + (OCTAVELENGHT * 3), OCTAVE4S) def terminate(): pygame.quit() sys.exit() def drawWood(): pygame.draw.rect(DISPLAYSURF, BROWN, (WHITESTARTCOORDX, WINDOWHEIGHT - 180, OCTAVELENGHT * 4, 44)) pygame.draw.rect(DISPLAYSURF, FIREBRICK, (WHITESTARTCOORDX, WINDOWHEIGHT - 180, OCTAVELENGHT * 4, 45), 1) def checkForQuit(): for event in pygame.event.get(QUIT): # get all the QUIT events terminate() # terminate if any QUIT events are present for event in pygame.event.get(KEYUP): # get all the KEYUP events if event.key == K_ESCAPE: terminate() # terminate if the KEYUP event was for the Esc key pygame.event.post(event) # put the other KEYUP event objects back def generateWhiteFrets(WHITESTARTCOORDX, OCTAVE): for i in range(0,7): fret = pygame.Rect(WHITESTARTCOORDX, WINDOWHEIGHT - 135, WHITEFRETWIDTH, WHITEFRETHEIGHT) pygame.draw.rect(DISPLAYSURF, WHITE, fret) associateWhiteNote(fret, OCTAVE, i) WHITESTARTCOORDX += WHITEFRETWIDTH + 1 # + 1 to separate frets def generateBlackFrets(BLACKSTARTCOORDX, OCTAVE): for i in range(0,6): if i == 2: BLACKSTARTCOORDX += BLACKGAPSIZE else: fret = pygame.Rect(BLACKSTARTCOORDX, WINDOWHEIGHT - 135, BLACKFRETWIDTH, BLACKFRETHEIGHT) pygame.draw.rect(DISPLAYSURF, BLACK, fret) associateBlackNote(fret, OCTAVE, i) BLACKSTARTCOORDX += BLACKGAPSIZE def associateWhiteNote(fret, OCTAVE, index): if index == 0: OCTAVE['C'] = fret elif index == 1: OCTAVE['D'] = fret elif index == 2: OCTAVE['E'] = fret elif index == 3: OCTAVE['F'] = fret elif index == 4: OCTAVE['G'] = fret elif index == 5: OCTAVE['A'] = fret elif index == 6: OCTAVE['B'] = fret def associateBlackNote(fret, OCTAVE, index): if index == 0: OCTAVE['C#'] = fret if index == 1: OCTAVE['D#'] = fret if index == 3: OCTAVE['F#'] = fret if index == 4: OCTAVE['G#'] = fret if index == 5: OCTAVE['A#'] = fret |
|
|
|
|
|
#4 |
|
Senior Member
Iscritto dal: Mar 2007
Città: Milano Beach
Messaggi: 1696
|
Mmm, principalmente non funziona perchè nel main non viene dichiarata alcuna istanza della classe basePPT.
Ma soprattutto, perchè hai racchiuso tutti i metodi nella classe basePPT? Ad occhio non ce n'era alcun bisogno..
__________________
~ Cthulhu: MacBookPro 13.3" ~ Azathoth: D510MO |
|
|
|
|
|
#5 |
|
Member
Iscritto dal: Mar 2011
Messaggi: 125
|
Giusto per avere il codice un po' più in ordine :/ comunque è vero, il problema è quello
Il punto è che anche facendo Codice:
from basePPT import * Comunque il codice al momento e sulle 460 righe, ma credo di non essere ancora a metà della sua stesura definitiva, quindi credo che per una lunghezza simile dividere il codice potrebbe essere una buona idea. Non dico sia una lunghezza assurda, ma neanche troppo breve. Sbaglio? |
|
|
|
|
|
#6 |
|
Senior Member
Iscritto dal: Mar 2007
Città: Milano Beach
Messaggi: 1696
|
Bah, se non hai necessità di estendere (aka personalizzare) la classe la trovo una cosa inutile
Praticamente stai usando la classe come namespace... il namespace in questo caso è già il modulo, quindi è inutile crearne uno ulteriore. Per quanto riguarda l'organizzazione, personalmente penso che la cosa dipenda da quello che fa il codice. Sempre attenzione all'import *, non sai mai bene quello che viene importato e corri il rischio di "mettere in ombra" oggetti locali.
__________________
~ Cthulhu: MacBookPro 13.3" ~ Azathoth: D510MO |
|
|
|
|
|
#7 |
|
Member
Iscritto dal: Mar 2011
Messaggi: 125
|
Ok, ho capito che in questo caso la classe è un po' uno spreco.
Tuttavia non ho ancora ben chiaro se esiste o meno un modo per farmi tenere le funzioni separate dal resto e permettermi di usare senza scrivere basePPT ogni volta. Puoi spiegarmi per favore? Inoltre sai perché non funziona import * in questo caso? |
|
|
|
|
|
#8 |
|
Senior Member
Iscritto dal: Mar 2007
Città: Milano Beach
Messaggi: 1696
|
import crea, nel namespace attuale, un riferimento a ciò che viene definito nel top level del modulo importato, quindi per accedere a tutto quello che è all'interno di classi o simili devi passare attraverso tale riferimento.
A questo punto hai queste alternative: - Scrivi le funzioni nel top level del modulo (quindi non all'interno di classi o simili) e le importi con from basePPT import *. In questo modo potrai chiamarle senza anteporre basePPT - Le dichiari all'interno di una classe (magari statiche col decorator @staticmethod) e le usi attraverso il nome della classe, quindi basePPT.nome_metodo() A te scegliere quale.
__________________
~ Cthulhu: MacBookPro 13.3" ~ Azathoth: D510MO |
|
|
|
|
|
#9 |
|
Member
Iscritto dal: Mar 2011
Messaggi: 125
|
Beh, la seconda
Grazie mille |
|
|
|
|
| Strumenti | |
|
|
Tutti gli orari sono GMT +1. Ora sono le: 17:13.



















