简体   繁体   中英

Python modules - Scopes

I found what I think is peculiar behaviour by python 3.4. I made these small files to illustrate the problem I am facing.

To focus on the problem, I now have a python program(module), peculiar.py, containing a class, and some functions. One of the functions are instantiating points from the class Point. When I left click the pygame window, a point is instantiated from the class Point, by this function, add_point. In the command window the instances created this way is listed. Everything is ok with this. As we can see the points crated are added to the points_list and listed in the command window.

Right clicking the window makes the very same function (add_point) called by a function in another module (pec_controls.py). A point is then instantiated, but it seems to be added to a new or different points_list, adding only points instantiated by right clicking the window. If we toggle between right and left clicking the window, the class toggles between two different versions of the points_list.

I could understand this behavior if the class was called directly from pec_controls.py, ie the point was instantiated in pec_control.py, but not as now, when it is the very same function in peculiar.py that calls the class in all instances. I am kind of "passing the scope" to pec_control module when I right click, but I think one should expect the scope to be returned, when that module then calls add_point, back in peculiar.py. It is very unexpected to put it mildly that where you call a function from is significant to it's, and or, a class's behavior.

Could someone explain the rationale behind this behavior by python? Is there something I forgot, to make all the instances appear in the same list?

Here is pec_controls.py:

import peculiar, sys, pygame

def clicked_right():
    peculiar.add_point()

and here is peculiar.py:

# peculiar.py
# Sample to show peculiar behaviour by python 3.4, or python in general?
# Left clicking window instantiates point by this module alone(see command window).
# Right clicking window instantiates point from pec_controls.py module. 
# Right clicking, instead of calling add_point function directly, as left clicking does, calls     function in pec_controls.py, which then calls the add_point function in this module.
# What is peculiar is that this is resulting in Class Point seeming to make a new list of the global list points_list,
# only containing the items instantiated from pec_controls module(i.e. by right clicking window) ref. command window .
# Left clicking again, makes the Class go back to the original list, adding "leftclicked" point instances as usual.
# Apparently there is now two different lists? Is this a bug or intended? 

import pygame, sys, pec_controls
from pygame.locals import *

FPS = 10
points_list = []
class Point():
    def __init__(self):
        points_list.append(self)
        self.position = (10 * len(points_list), 10 * len(points_list))
        print("Class says:    ",len(points_list), "points")                     

    def update(self):
        self.rect.x = self.position[0]
        self.rect.y = self.position[1]
        pass

def add_point( x = None, y = None):
    display_frame()
    point = Point()
    for i in points_list:                                                       # The points created by calling the class from controls.py via btn_add_point_clicked_left.
        print ("add_point says", i, i.position)                                 # ref: Display frame which prints out the points made by calling the class from main
   print ("add_point", points_list)                                             # This writes out points in points_list                     !!!!!!!!


def process_events():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                return True
            if event.type == pygame.MOUSEBUTTONUP :
                if event.button == 1:
                    add_point()                                     # Instantiates a point via btn_add_point_clicked. (Ok/Normal)
                    print("Left Click")
                elif event.button == 3:
                    pec_controls.clicked_right()                                # Instantiates a point via pec_controls module via add_point. (Peculiar result !!!!)
                    print("Right Click")    
                pass
        return False

def display_frame():                                        
    for i in points_list:                                   # Writes out the points in the global list points_list
        print ("display says", i, i.position)                   # 
    print("display", points_list)                               # 

def main():                                                 # Main function
    pygame.init()
    main.screen = pygame.display.set_mode((200,200),0,32)
    main.clock = pygame.time.Clock()

    point = Point()                                         # Instantiates a point from main of this module
    point.position =(100,200)

    add_point()                                             # Instatiates a point from main via the function add_point

    main.done = False
    while not main.done:                                    
        main.done = process_events()
        main.clock.tick(FPS)
        #display_frame()

    pygame.quit()   

if __name__ == "__main__":
    main()

The problem you're running into is that when peculiar.py is run as a script, it is not considered to be the peculiar module. It is considered to be the __main__ module. Importing peculiar will run the file again, producing a separate copy of the Point class, the points_list list, and so on.

I recommend separating your program's main functionality into a separate file that imports peculiar and calls the versions of everything from the peculiar module. Alternatively, you can use import peculiar; peculiar.main() import peculiar; peculiar.main() in your if __name__ == "__main__" block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM