persistence of objects in python

2019-09-22 04:03发布

Till now I have done only procedural programming in C so I am rather unclear about both OOP and Python.

I have a large project which contains a number of python files. File a.py defines a class called fobject I am using python 2.5

File b.py and c.py have classes called BProject and CProject which have an object of fobject as parameter. I have included using import CProject (defined in c.py) in b.py. I have a list in CProject which I fill using wx python GUI. Next I call a function BRun defined in BProject which internally calls a CRun Function in CProject ie. in c.py.

In this CRun I want to manipulate the list but list is always empty at this time. Why is this so?

What should I do given the constraint is I can't change anything a.py in which fobject is defined ?

file : c.py

def Instance(fObject):
    return test_page_CProject(fObject)


class CProject(object):

    def __init__(self, fObject):
        self.fObj = fObject
        self.IntList  =  []
        ##snip


    def  OnIntSelectBtnPress(self,parent):
        print ":self.IntList"
        print self.IntList
        self.listBoxIntSelect.InsertItems(self.IntList,0)
        print self.IntList


    def OnIntRun(self):

                IntLModeList = self.IntListIntMode
                #snip

file b.py

def Instance(fObject):
    return BProject(fObject)

class BProject(object):

    def __init__(self, fObject):

        self.FObj = fObject
        #snip
        Object = __import__('CProject')
        #snip

        self.intObject = Object.Instance(self.FObj)
        self.intObject.OnIntRun()

1条回答
老娘就宠你
2楼-- · 2019-09-22 05:08

You don't understand python. You need to understand variables (almost everything in python is basically a pointer), and namespaces.

OK, so you don't understand when python creates new objects.

In 90% of cases, every time you see an object, it will be a new one.

For example:

a = [1,2,3]
b = a + [4,5] 
print a
>>> [1,2,3]

See? b is a new object, a is untouched.

Also:

def func(a):
    a = [1,2,3]+a 
    return a

a = [4,5]
print func(a)
>>> [1,2,3,4,5]
print a
>>> [4,5]

Why did this happen? Inside the function, there's a whole new namespace (which is probably something like a new stack). So the new a inside the function has nothing to do with the old a outside the function.

It's really hard to make python share data, which makes it really hard for one section of code to mess with variables in another area.

You can alter stuff, but you have to jump through hoops:

def func(a):
    a.append([4,5])
    return a

a = [1,2,3]
print func(a)
>>> [1,2,3,4,5]
print a
>>> [1,2,3,4,5]

See, it worked! I altered a, because I used a method of a, not creating a new variable.

查看更多
登录 后发表回答