Python: how to refer to an instance name?

后端 未结 4 1597
北恋
北恋 2021-01-14 01:45

I\'m collecting instances using the following code:

class Hand():
    instances = []
    def __init__(self):
        Hand.instances.append(self)
        self         


        
4条回答
  •  悲&欢浪女
    2021-01-14 02:22

    If you mean how to get hand1 from the instance you assigned to self.hand1, the answer is that you can't. When you do self.hand1 = Hand(), you tell the Foo object it has a Hand, but the Hand object has no knowledge that it has been assigned to a Foo. You could do this:

    h = Hand()
    self.bob = h
    self.larry = h
    

    Now what is the "name" of that Hand supposed to be? You assigned the same hand to both "bob" and "larry", so there's no way it can have a single unique name.

    If you want to have a name for each hand, you need to tell the hand what name you want to give it. You would have to modify your Hand code to allow you to pass a name to the constructor, then create the Hand with Hand("some name").

    You can of course give the hands "names" by assigning attributes on them:

    self.hand1 = Hand()
    self.hand1.name = "hand 1"
    

    . . . but these names are not special or "automatic" in any way.

    The bottom line is that if you want something to have a name, you need to decide how to handle that name. You need write your own code that gives it its name, and your own code that retrieves its name.

提交回复
热议问题