Python Remote Object

Why is this not working? I am trying to make an instance of the delete class.

>>> class A(): def kill(self): del self >>> a = A() >>> a.kill() >>> a <__main__.A instance at 0x01F23170> 
+58
python memory-management instance
Nov 16 '08 at 3:29
source share
13 answers

'self' is just an object reference. del del removes the self link from the local namespace of the kill function instead of the actual object.

To verify this, look at what happens when these two functions are executed:

 >>> class A(): ... def kill_a(self): ... print self ... del self ... def kill_b(self): ... del self ... print self ... >>> a = A() >>> b = A() >>> a.kill_a() <__main__.A instance at 0xb771250c> >>> b.kill_b() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in kill_b UnboundLocalError: local variable 'self' referenced before assignment 
+67
Nov 16 '08 at 3:41
source share

You do not need to use del to delete instances in the first place. As soon as the last reference to the object disappears, the object will be garbage collected. Maybe you should tell us more about the complete problem.

+42
Nov 16 '08 at 3:46
source share

In this particular context, your example does not make much sense.

When Genesis picks up the Item, the item maintains an individual existence. He does not disappear, because they pick him up. He still exists, but he (a) is in the same place as the Being, and (b) can no longer be chosen. Despite the change in state, it still exists.

There is a two-way connection between Being and the Element. The creature has an Item in its collection. The element is associated with the Being.

When an item is picked up by a Being, two things must happen.

  • Being is how to add Item to some set elements. For example, your bag attribute might be such a set . [A list - bad choice - does the order of things in the bag?]

  • The location of the element changes from where it was to the place of Being. There are probably two classes of os Items - those that have an independent sense of location (because they move on their own) and objects that should delegate the location of the Creature or the Place where they sit.

In no case should any Python object be deleted. If the item is "destroyed", then this is not in the bag of Genesis. This is not in place.

 player.bag.remove(cat) 

This is all it takes to let the cat out of the bag. Since the cat is not used anywhere, it will exist as a "used" memory and does not exist, because nothing in your program can access it. It will quietly disappear from memory when a quantum event occurs, and references to memory are garbage collection.

On the other hand,

 here.add( cat ) player.bag.remove(cat) 

Put the cat in its current location. The cat continues to exist and will not be extinguished with litter.

+13
Nov 16 '08 at 14:26
source share

I think I finally understood!
NOTE. You should not use this in regular code , but it is possible. This is just for curiosity, see Other answers for real solutions to this problem.




Take a look at this code:
 # NOTE: This is Python 3 code, it should work with python 2, but I haven't tested it. import weakref class InsaneClass(object): _alive = [] def __new__(cls): self = super().__new__(cls) InsaneClass._alive.append(self) return weakref.proxy(self) def commit_suicide(self): self._alive.remove(self) instance = InsaneClass() instance.commit_suicide() print(instance) # Raises Error: ReferenceError: weakly-referenced object no longer exists 

When an object is created in the __new__ method, the instance is replaced by a proxy server with a weak link, and the only reliable link is stored in the attribute of the _alive class.

What is a weak link?

A weak link is a link that is not considered a link when the garbage collector collects an object. Consider this example:

 >>> class Test(): pass >>> a = Test() >>> b = Test() >>> c = a >>> d = weakref.proxy(b) >>> d <weakproxy at 0x10671ae58 to Test at 0x10670f4e0> # The weak reference points to the Test() object >>> del a >>> c <__main__.Test object at 0x10670f390> # c still exists >>> del b >>> d <weakproxy at 0x10671ab38 to NoneType at 0x1002050d0> # d is now only a weak-reference to None. The Test() instance was garbage-collected 

Thus, the only reliable reference to the instance is stored in the attribute of the _alive class. And when the commit_suicide () method removes the link, the instance is collected by the garbage collector.

+11
Aug 13 '16 at 11:55
source share

Actually, you do not need to delete the object in order to do what you are trying to do. Instead, you can change the state of the object. An example of how this works, without falling into the encoding, will be your player fighting a monster and killing a monster. The state of this monster is fighting. The monster will have access to all the methods necessary for the fight. When a monster dies because its health drops to 0, the state of the monsters will change to dead, and your character will automatically stop the attack. This methodology is very similar to using flags or even keywords.

It is also obvious that python deletion classes are not required, as they will automatically be garbage collected if they are no longer in use.

+4
Sep 28
source share

I cannot tell you how this is possible with classes, but functions can be deleted by themselves.

 def kill_self(exit_msg = 'killed'): global kill_self del kill_self return exit_msg 

And look at the result:

  >>> kill_self <function kill_self at 0x02A2C780> >>> kill_self() 'killed' >>> kill_self Traceback (most recent call last): File "<pyshell#28>", line 1, in <module> kill_self NameError: name 'kill_self' is not defined 

I do not think that deleting a single instance of a class without knowing its name is possible.

Note: If you assign a different function name, the other name will still refer to the old one, but will cause errors after trying to run it:

 >>> x = kill_self >>> kill_self() >>> kill_self NameError: name 'kill_self' is not defined >>> x <function kill_self at 0x...> >>> x() NameError: global name 'kill_self' is not defined 
+3
Aug 08 '10 at 17:33
source share

I am trying to do the same. I have an RPG combat system in which my Death (self) function must kill its own object in the Fighter class. But it turned out to be impossible. Perhaps my cool game, in which I collect all the participants in the battle, should remove units from the "fictional" map.

  def Death(self): if self.stats["HP"] <= 0: print("%s wounds were too much... Dead!"%(self.player["Name"])) del self else: return True def Damage(self, enemy): todamage = self.stats["ATK"] + randint(1,6) todamage -= enemy.stats["DEF"] if todamage >=0: enemy.stats["HP"] -= todamage print("%s took %d damage from your attack!"%(enemy.player["Name"], todamage)) enemy.Death() return True else: print("Ineffective...") return True def Attack(self, enemy): tohit = self.stats["DEX"] + randint(1,6) if tohit > enemy.stats["EVA"]: print("You landed a successful attack on %s "%(enemy.player["Name"])) self.Damage(enemy) return True else: print("Miss!") return True def Action(self, enemylist): for i in range(0, len(enemylist)): print("No.%d, %r"%(i, enemylist[i])) print("It`s your turn, %s. Take action!"%(self.player["Name"])) choice = input("\n(A)ttack\n(D)efend\n(S)kill\n(I)tem\n(H)elp\n>") if choice == 'a'or choice == 'A': who = int(input("Who? ")) self.Attack(enemylist[who]) return True else: return self.Action() 
+3
Dec 08 2018-11-12T00:
source share

Indeed, Python does garbage collection through reference counting. As soon as the last object reference falls out of scope, it is deleted. In your example:

 a = A() a.kill() 

I do not believe that there was no value for the variable 'a', so that it did not point to None.

+1
Nov 16 '08 at 3:59
source share

If you use a single link to an object, then the object can kill itself by dropping this external link to itself, as in:

 class Zero: pOne = None class One: pTwo = None def process(self): self.pTwo = Two() self.pTwo.dothing() self.pTwo.kill() # now this fails: self.pTwo.dothing() class Two: def dothing(self): print "two says: doing something" def kill(self): Zero.pOne.pTwo = None def main(): Zero.pOne = One() # just a global Zero.pOne.process() if __name__=="__main__": main() 

Of course, you can control the logic by checking the existence of an object outside the object (and not the state of the object), for example, in:

 if object_exists: use_existing_obj() else: obj = Obj() 
+1
Feb 01 '13 at 11:27
source share

I am curious why you would like to do this. Most likely, you should just let the garbage collection do its job. In python, garbage collection is pretty deterministic. Therefore, you do not need to worry about just leaving the objects that are in memory, as in other languages ​​(not to mention the fact that recalculation has no drawbacks).

Although one thing you should consider is wrapping around any objects or resources that you can get rid of later.

 class foo(object): def __init__(self): self.some_big_object = some_resource def killBigObject(self): del some_big_object 

In response to Null addendum :

Unfortunately, I do not think that there is a way to do what you want to do the way you want. Here is one way you might want to consider:

 >>> class manager(object): ... def __init__(self): ... self.lookup = {} ... def addItem(self, name, item): ... self.lookup[name] = item ... item.setLookup(self.lookup) >>> class Item(object): ... def __init__(self, name): ... self.name = name ... def setLookup(self, lookup): ... self.lookup = lookup ... def deleteSelf(self): ... del self.lookup[self.name] >>> man = manager() >>> item = Item("foo") >>> man.addItem("foo", item) >>> man.lookup {'foo': <__main__.Item object at 0x81b50>} >>> item.deleteSelf() >>> man.lookup {} 

This is a bit messy, but it should give you this idea. In fact, I do not think that linking the existence of an element in a game to whether it is a good idea highlighted in memory. This is because the conditions for collecting garbage are likely to differ from the conditions for the item in the game. So you don’t need to worry so much about it.

0
Nov 16 '08 at 4:19
source share

what you could do is take a name with you in the class and do dictionairy:

 class A: def __init__(self, name): self.name=name def kill(self) del dict[self.name] dict={} dict["a"]=A("a") dict["a"].kill() 
0
Mar 25 '15 at 11:36
source share
 class A: def __init__(self, function): self.function = function def kill(self): self.function(self) def delete(object): #We are no longer in A object del object a = A(delete) print(a) a.kill() print(a) 

Can this code work?

0
Oct 29 '18 at 19:52
source share

This is what I have done in the past. Create a list of objects, and then you can delete the objects yourself using list.remove() .

 bullet_list = [] class Bullet: def kill_self(self): bullet_list.remove(self) bullet_list += [Bullet()] 
0
Nov 18 '18 at
source share



All Articles