Determine the container class of an object in Python 3
Steve D'Aprano
steve+python at pearwood.info
Wed Oct 25 22:25:19 EDT 2017
On Thu, 26 Oct 2017 12:25 pm, qrious wrote:
> Class1 is instantiated in Class2 as follows. Class2 also contains another
> variable, say:
>
> class Class2:
> class1 = Class1()
> a = 0
>
> I want to create a method myDef() in Class1 that can read or write to a. How
> do I access a from within myDef() to access a?
The only way is to hard-code the name "Class2" in myDef.
But the usual way to fix this problem is:
class Class1:
def __init__(self, owner):
self.owner = owner
def myDef(self):
return self.owner.a
def Class2:
def __init__(self):
self.class1 = Class1(self)
self.a = 0
Technically, it is a circular reference, but don't worry about it, Python's
garbage collector can resolve such circular references. If it becomes a
problem -- and it shouldn't, but if it does -- you can use a weakref. But
seriously, don't worry about it unless you need to.
Another solution is to make Class1 a mixin, and then rely on inheritence:
class MyMixin:
def myDef(self):
return self.a
class Class2(MyMixin):
def __init__(self):
self.a = 0
--
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.
More information about the Python-list
mailing list