Accessing higher-level class from nested class in Python - python

Suppose I have two Python classes, A and B, and that B is an attribute of A. Can a method of B modify a property of A? for example, I would like to be able to call
A.B.setXinA(1)
A.x
>>> 1
One way around it would be embed a reference to A in B:
A.B.reftoA = A
But that's rather ugly... Is there a way to access the higher-level class directly? Below is a working example using the second method:
class A:
def __init__(self, b):
b.parent = self
setattr(self, b.name, b)
class B:
def __init__(self, name):
self.name = name
b = B('abc')
a = A(b) # b is now a.abc
abc.parent.x = 1
a.x
>>> 1

What about a method in B like this:
class B:
def __init__(self, name):
self.name = name
def setXinA(self, x):
self.parent.x = x
Then:
>>> b = B('abc')
>>> a = A(b)
>>> b.setXinA(19)
>>> print(A.x)
19
This way requires that setXinA is called by an instance of B rather than just B.setXinA(42) for example. Also, it sets x as an attribue of the class A, rather than any particular instance of A.

Related

Unpacking a class [duplicate]

This question already has answers here:
Class that acts as mapping for **unpacking
(3 answers)
Implement packing/unpacking in an object
(4 answers)
Closed last year.
I'd like to make a class that unpacks it's objects like a dictionary.
For example, with a dictionary you can do this
foo = {
"a" : 1
"b" : 2
}
def bar(a,b):
return a + b
bar(**foo)
outputs 3
And I'd like to be able to do this
class FooClass:
def __init__(self):
self.a = a
self.b = b
f = FooClass()
bar(**f)
and have it output 3
This is the most related question I could find but it doesn't address this so I'm thinking it might not be possible.
Currently what my solution would be this:
class FooClass:
def __init__(self):
self.a = a
self.b = b
def to_dict(self):
return {
"a" : self.a,
"b" : self.b
}
f = FooClass()
bar(**f.to_dict())
As pointed out in the comments, writing a conformant subclass of the collections.abc.Mapping abstract class is the way to go. To (concretely) subclass this class, you need to implement __getitem__, __len__, and __iter__ to behave consistently like a dictionary would. So that means __getitem__ expects a string, __iter__ returns an iterable of strings, etc.
For a simple example, we'll simply delegate all of these to self.__dict__, but in real code you'd likely want to do something more refined.
from collections.abc import Mapping
class FooClass(Mapping):
def __init__(self, a, b):
self.a = a
self.b = b
def __getitem__(self, x):
return self.__dict__[x]
def __iter__(self):
return iter(self.__dict__)
def __len__(self):
return len(self.__dict__)
def bar(a, b):
return a + b
foo = FooClass(40, 2)
print(bar(**foo))
Aside from reyling on vars(f) or f.__dict__, you could use a dataclass.
from dataclasses import dataclass, asdict
#dataclass
class FooClass:
a: int
b: int
Demo:
>>> f = FooClass(1, 2)
>>> asdict(f)
{'a': 1, 'b': 2}
def bar(a, b):
return a + b
class FooClass:
def __init__(self, a, b):
self.a = a
self.b = b
f = FooClass(1, 2)
print(bar(*f.__dict__.values()))
# print(bar(**f.__dict__)) # Also works
Output:
3

Access all variables by their names of specific object in class

I have two python classes:
class A:
def __init__(self, param1):
self.param1 = param1
class B:
def __init__(self, a):
self.a = a
Now I have an instance of B and need to access param1, I can just write b.a.param1. But the goal is to omit the 'a' part, so access this param with b.param1. I could add property to class B, but I am searching for generic solution - when A class has a lot variables. Is it possible? And would it be clean solution?
This is not the most elegant option and probably a bad practice but you can copy all the attributes of a to be attributes of b using getattr and setattr:
import inspect
class A:
def __init__(self, param1):
self.param1 = param1
class B:
def __init__(self, a):
self.a = a
variables = [i for i in dir(a) if not inspect.ismethod(i) and i[:2] != '__']
for var in variables:
setattr(self, var, getattr(a, var))
This way you can access a's attributes directly:
a = A(1)
b = B(a)
b.param1
which will return
1

How to access objects from a different class?

There are three classes :
A, B and C
The __init__ of B creates an object of A. Using the mutators, I will be able to change the attributes of A from B for the instance created.
However, I am not unable to find any way to use that instance of A created by B to be used in C without passing the Object explicitly to the __init__ method [ not C.__init(self, object: A) ]
Is there any way to implicitly allow C to use that instance of A ?
I am new to python and not sure if this a valid question. I have looked at other sources where it explicitly passes the object to class C
class A:
def __init__(self):
x = []
y = []
class C :
def __init__(self):
#[get obj1 without passing the instance in init]
self.value = None
def method1():
self.value = len([]) #len(obj1 of A.x)
class B:
def __init__(self):
obj1 = A()
obj1.x = [1,2,3,4]
obj1.y = [1,2,3]
obj2 = B()
print(obj2.value) #this should be the length of x in the instance A created above
Here is a simple example:
class A:
def __init__(self, i = ""):
self.item = i
class B:
def __init__(self):
self.a = A("hello")
class C:
def __init__(self):
b = B()
print(b.a.item)
c = C()
Output:
hello
Let's say we have classes A and B:
class A:
def hello_world(self):
print("hello world")
class B:
def __init__(self):
self.a = A()
def hello_world(self):
self.a.hello_world()
You create an instance of class B (which will create an instance of class A inside):
b = B()
You can then pass a reference to either b or b.a to any function of an instance of class C (either a constructor or not)
class C:
def hello_world(self, a):
a.hello_world()
c = C()
c.hello_world(b.a)
You can also use global variables:
class C:
def hello_world(self):
b.a.hello_world()
c = C()
c.hello_world()
Here the instances of class C will rely on variable b to be in place and just use its a attribute.
Using global variables in classes is generally considered to be hard to maintain and a bad practice. If your class depends on a value or an instance of some class you should pass the reference in the constructor (__init__ function) or in the function that's using it.
If these classes are in different different python files then you can also use these classes by importing the class name and creating an object of that class:
eg:
file1.py
class A:
def __init__(self):
x = []
y = []
file2.py
from file1 import A
class C :
def __init__(self):
[get obj1 without passing the instance in init]
self.value = None
self.obj_a = A()
def xyz(self):
print "in class c"
file3.py
from file2 import C
from file1 import A
Class B:
def __init__(self):
self.obj_a = A()
self.obj_c = C()
def another_func(self):
print self.obj_c.xyz()# it will print "in class c"

How can i have 2 classes reference the same instance of a class

I have class A class B and class C.
class A and B can affect class C. so they need to refer to the same instance of the class.
#a.py
from C import C
Cinstance = C()
Cinstance.add()
#b.py
class b(object)
#i need to refer to 'cinstance' here to control the same instance of the class
#C.py
class C(object)
def __init__(self):
self.a=1
def add(self):
self.a += 1
print a
How do i need to import and instanciate the classes for it to work this way? I am new to programming and still learning so things that are obvious are still a little difficult for me right now.
class A:
def __init__(self,cInst):
self.c = cInst
class B:
def __init__(self,cInst):
self.c = cInst
cInst = C()
a = A(cInst)
b = B(cInst)
something like that maybe
based on what you have there I think the easiest thing would be to import Cinstance from module a.
from a import Cinstance
You can pass an instance of A and B to your C.__init__ method and save them as attributes of C.
I'm on my phone, so the code below isn't tested
class C(object):
def __init__(self, a, b):
self.a = a
self.b = b
>>> c = C(A(), B())

Python object conversion

Assume that we have an object k of type class A. We defined a second class B(A). What is the best practice to "convert" object k to class B and preserve all data in k?
This does the "class conversion" but it is subject to collateral damage. Creating another object and replacing its __dict__ as BrainCore posted would be safer - but this code does what you asked, with no new object being created.
class A(object):
pass
class B(A):
def __add__(self, other):
return self.value + other
a = A()
a.value = 5
a.__class__ = B
print a + 10
a = A() # parent class
b = B() # subclass
b.value = 3 # random setting of values
a.__dict__ = b.__dict__ # give object a b's values
# now proceed to use object a
Would this satisfy your use case? Note: Only the instance variables of b will be accessible from object a, not class B's class variables. Also, modifying variables in a will modify the variable in b, unless you do a deepcopy:
import copy
a.__dict__ = copy.deepcopy(b.__dict__)
class A:
def __init__(self, a, b):
self.a = a
self.b = b
class B(A):
def __init__(self, parent_instance, c):
# initiate the parent class with all the arguments coming from
# parent class __dict__
super().__init__(*tuple(parent_instance.__dict__.values()))
self.c = c
a_instance = A(1, 2)
b_instance = B(a_instance, 7)
print(b_instance.a + b_instance.b + b_instance.c)
>> 10
Or you could have a sperate function for this:
def class_converter(convert_to, parent_instance):
return convert_to(*tuple(parent_instance.__dict__.values()))
class B(A):
def __init__(self, *args):
super().__init__(*args)
self.c = 5
But using the 2nd method, I wasn't able to figure out how to pass additional values

Categories