Reputation: 11
In Python, I have a
class OBJECT
that is initialized. I am now creating a new class that will need to use methods of this object. If I do:
class NEW_CLASS:
def __init__(self, Object):
self.Object = Object
NEW_CLASS(OBJECT)
Does self.Object work like a pointer (excuse the terminology, originally a C programmer) where it points to OBJECT (my desired result) or does self.Object create a separate OBJECT within NEW_CLASS? If it doesn't act like a pointer, how can I implement this behavoir?
I will have one OBJECT in my project but many NEW_CLASS and NEW_CLASS will need to access OBJECT. I don't want to create a new copy for each NEW_CLASS.
Thanks for the help!
Upvotes: 1
Views: 221
Reputation: 7129
No doubt it is the same of object. And they both have the same id
, meaning memory location in C/C++.
>>> id(NEW_CLASS(OBJECT).Object) == id(OBJECT)
True
id(...)
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
One advice, avoid using object
(irrespective of cases) as a variable name.
help(object)
class object
| The most base type
Upvotes: 0
Reputation: 11545
So, you want OBJECT
to be a global object?
How about (stylized to follow Python conventions):
class GlobalObject:
"""Insert class definition here."""
OBJECT = GlobalObject()
class MyClass:
def __init__(self, global_object=OBJECT):
self._object = global_object
def do_something():
print "The object is: %s" % self._object
Upvotes: 0
Reputation: 122436
It will indeed behave as a pointer. So every time you access self.Object
you'll be accessing the same Object
that was initially passed to a new instance of the class NEW_CLASS
.
Upvotes: 2