kra*_*r65 4 python class object
我有一个简单的类,我可以从中创建两个对象.我现在想要从类中打印对象的名称.所以像这样:
class Example:
def printSelf(self):
print self
object1 = Example()
object2 = Example()
object1.printSelf()
object2.printSelf()
Run Code Online (Sandbox Code Playgroud)
我需要这个打印:
object1
object2
Run Code Online (Sandbox Code Playgroud)
不幸的是,这只是打印 <myModule.Example instance at 0xb67e77cc>
有人知道我怎么做吗?
object1 只是指向实例对象的标识符(或变量),对象没有名称.
>>> class A:
... def foo(self):
... print self
...
>>> a = A()
>>> b = a
>>> c = b
>>> a,b,c #all of them point to the same instance object
(<__main__.A instance at 0xb61ee8ec>, <__main__.A instance at 0xb61ee8ec>, <__main__.A instance at 0xb61ee8ec>)
Run Code Online (Sandbox Code Playgroud)
a,b,c都是简单的引用,使我们能够访问相同的对象,当一个对象具有0引用,它会自动进行垃圾回收.
快速入侵将在创建实例时传递名称:
>>> class A:
... def __init__(self, name):
... self.name = name
...
>>> a = A('a')
>>> a.name
'a'
>>> foo = A('foo')
>>> foo.name
'foo'
>>> bar = foo # additional references to an object will still return the original name
>>> bar.name
'foo'
Run Code Online (Sandbox Code Playgroud)