How to access Python objects within objects in Python?
Answers
I write a program in Python. I Have class A. one of its variables,v, is an instance of another class, B:
class A:
def __init__(self):
self.v = B()
the class B in in the form of:
class B:
def __init__(self):
self.list = [1,2,3]
def function(self):
self.list[2] = 1
I create an instance x=A(), put it in a list g (g=[x]) and then change one of the variables in x.v by printing g[0].v.function(). However, when I ask the computer to print g[0].v.list, it prints [1,2,3] rather then [1,2,1]. What can be the reason?
Thank you.
Python objects within objects in Python
Explanation:
#define class
class main:
#define constructor
def __init__(self):
self.w = nex()
#definr class
class nex:
#define constructor
def __init__(self):
self.l = [3,4,5]
#define function
def fun(self):
self.l[2] = 7
#set class object and call constructor
ob = main()
q = [ob]
#call and print function.
print(q[0].w.fun())
print(q[0].w.l)
Following are the description of the program:
- Define class 'main' and inside the class we define constructor of the class.
- Then, we define class 'nex' and inside the class we define constructor that contain list and then define function that change the third index of the list.
- Finally, set the object of the class and call constructor, then print and call the function.
Learn More:
brainly.com/question/13105800