everyone. I would need help to understand how to select a parameter of a class. I am studying them now and can't figure out how to select the data I need.
As you can see from the code below, I would like to get the value of Xxxx() in a3 or a4, it makes no difference, but I don't understand what should I do? How do I select it and use it in a variable or print it out?
Thanks for the help
class Xxxx_Item:
""" """
def __init__(self, name, a1, a2, a3, a4):
self.name = name
self.a4 = a4
self.itemss = {
'a1': a1,
'a2': a2,
'a3': a3
}
class Xxxx:
""" """
def __init__(self):
self.xxx = [
Xxxx_Item(name="A", a1=1, a2=2, a3=3, a4=4)
]
base = Xxxx()
I've tried several ways but can't do it.
with print(base)
returns to me:
<__main__.Xxxx object at 0x000001FAF464E560>
I try:
base.xxx[1] # IndexError: list index out of range
base.xxx[Xxxx_Item[2]] # TypeError: 'type' object is not subscriptable
base.xxx[[0][2]] # IndexError: list index out of range
I am a bit puzzled about how the selection of a specific value within a class works.
CodePudding user response:
Xxxx_Item
contains a member named name
, a member named a4
and a member named itemss
that holds a dictionary from string to whatever's passed in.
Xxxx
contains member xxx
that holds a list containing one Xxxx_Item
To access members, you have to index into them appropriately:
a4
print(base.xxx[0].a4)
Start with base
, then access the member xxx
with .xxx
, then get the first item of this list with [0]
(which is an Xxxx_Item
), then access its a4
member with .a4
a3
print(base.xxx[0].itemss["a3"])
Start with base
, then access the member xxx
with .xxx
, then get the first item of this list with [0]
(which is an Xxxx_Item
), then access its itemss
member with .itemss
(which is a dictionary), then find what's in the "a3"
key with ["a3"]
Does this answer your question?
CodePudding user response:
I didnt understand why do you need second class but you can define methods to get every parameter you want in Xxxx_Item class, for example:
class Xxxx_Item:
def __init__(self, name, a1, a2, a3, a4):
self.name = name
self.a4 = a4
self.itemss = {
'a1': a1,
'a2': a2,
'a3': a3
}
def get_name(self):
return self.name
base = Xxxx_Item()
print(base.get_name())
If you want to use your second class you still define a method to get parameters, for example:
class Xxxx_Item:
def __init__(self, name, a1, a2, a3, a4):
self.name = name
self.a4 = a4
self.itemss = {
'a1': a1,
'a2': a2,
'a3': a3
}
def get_name(self):
return self.name
class Xxxx:
def __init__(self):
self.xxx = [
Xxxx_Item(name="A", a1=1, a2=2, a3=3, a4=4)
]
base = Xxxx()
print(base.xxx[0].get_name())