Python implements object instance modification through shelve, pythonshelve
This example describes how to modify objects through shelve in python.
The specific implementation method is as follows:
Import shelveshe = shelve. open ('try. she ', 'C') for c in 'spam': she [c] = {c: 23} for c in she. keys (): print c, she [c] she. close () she = shelve. open ('try. she ', 'C') print she ['P'] she ['P'] ['P'] = 42 # This modification won't work, this only modifies a temporary object print she ['P'] a = she ['P'] # binds a name a ['P'] = 42she ['P '] = aprint she ['P']
The test environment of this example is Python2.7.6.
The program running result is as follows:
P {'P': 23} a {'A': 23} m {'M': 23} s {'s': 23} {'P ': 23} # the original value is {'P': 23} # Only the temporary object {'P': 42} # is modified after the name is bound.
The instance code and running results are provided with detailed annotations to help you understand the meaning. I hope this article will help you with Python programming.
Source1 is an example of the basic python tutorial. For the shelve module
This is mentioned in the Python document (see the shelve module document): Because of Python semantics, a shelf cannot know when a mutable persistent-dictionary entry is modified. by default modified objects are written only when assigned to the shelf.
A shelf (object) cannot know when a variable item is modified. By default, a modified object takes effect only when it is assigned to the shelf object again.
The Python document also provides two solutions:
First, assign the modified object to the shelve object:
S ['X'] = s ['X']. append ('D') or, in a clearer form:
Temp = s ['X'] # obtain the copy of s ['X'], that is, a mutable list object temp. append ('D') # perform the append operation on this list object s ['X'] = temp # re-write back the second type:
S = shelve. open ('temp. dat ', writeback = True) # specify writeback as True. The default value is Falses ['X'] = ['A',' B ', 'C'] s ['X']. append ('D') s. close () in this way, the entry you want to access will be cached in memory, and the file will be written when you call the sync or close method.
Question about how to instantiate an object in python
Define a class to encapsulate all attributes, and then use the class object as the return value.
I don't know what you mean:
Class Node:
Def _ init _ (self, nodes, city, state, description = None ):
Self. nodes = nodes
Self. city = city
Self. state = state
Self. description = description
Def node_by_name (nodes, city, state ):
# Some other process
Description = 'North CAMBRIDGE'
Return Node (nodes, city, state, description)
Ans = node_by_name ('testnode', 'cambridge ', 'M ')
Print ans. state, ans. description