dictionary as a class argument in python - python

I am just starting Python for solving one project and I am struggling a lot with the syntax and usage as I have coded in type checking language only (Java, C++).
Here I am defining one class and inside that class, I want to store one dictionary of objects but I am not able to access that dictionary in other function of that class. below example give me the same error:
Code:
class abc:
def __init__(self):
a =10
class test:
def __init__(self):
self.ddict['xyz'] = abc()
def access(self):
self.ddict['def'] = abc()
I am getting the error:
self.ddict['xyz'] = abc()
AttributeError: test instance has no attribute 'ddict'

You need to initialize your dict before using it. You code should look like this:
class abc:
def __init__(self):
self.a = 10
class test:
def __init__(self):
self.ddict = {'xyz': abc()}

Thanks, #jonrsharpe. It worked!
class abc:
def __init__(self):
a =10
class test:
def __init__(self):
self.ddict = {} /* need to init first*/
self.ddict['xyz'] = abc()
def access(self):
self.ddict['def'] = abc()

Related

Setting self as an instance from another class doesn't work [Python]

Let's assume I have a class A and a class B.
class A:
def __init__(self):
self.variable1 = 1
self.variable2 = 'sometext'
class B:
def __init__(self, inst):
self = inst
print(self.__dict__.keys(), inst.__dict__.keys())
The print function returns
b = B(inst)
dict_keys(['variable1', 'variable2']) dict_keys(['variable1', 'variable2'])
However when I try
b.variable1
It returns the following error
AttributeError: 'B' object has no attribute 'variable1'
In my more complex code I need almost all variable from class A in class B.
I tried using class inheritance however I couldn't make it work with class methods and constructors.
Is there a reason why the above method doesn't work?
Thx
You're trying to overwrite self, but that only works while you're in the init. Instead, try assigning the inst to a variable of the class B:
class B:
def __init__(self, inst):
self.inst = inst
print(self.__dict__.keys(), inst.__dict__.keys())
Now you can access the variables of class A via:
inst = A()
b = B(inst)
b.inst.variable1
Not sure what you're trying to achieve here exactly, but you could also initiate the class A object inside the init of class B instead of passing the object to class B.
To use variable from class A in B you have to access to class A from B. Then execute class B
class A:
variable1 = 1
variable2 = 'sometext'
class B:
def __init__(self, inst=None):
self.f1 = A().variable1
self.f2 = A().variable2
def get_var(self):
print (self.f1)
B().get_var()

reference instance attribute in child class

I am trying to call an instance variable from a "parent" class (subclass) to it's "child" class (subsubclass)
class mainclass():
def __init__(self):
self.mainclassvar1 = "mainclass"
class subclass(mainclass):
def __init__(self):
self.subclassvar1 = "subclass"
def changeval(self):
self.subclassvar1 = "subclassedited"
class subsubclass(subclass):
def __init__(self):
self.subsubclassvar1 = subclass.subclassvar1 #<- naturally this fails
def handler():
main=mainclass()
sub = subclass()
sub.changeval()
subsub = subsubclass()
print(subsub.subsubclassvar1)# <- how do I achieve this? I would expect "subclassedited" but it doesn't
if __name__ == "__main__":
handler()
The above does not work obviously but I am trying to show what I am trying to achieve in my head.
if I change the class subsubclass(subclass) as follows it semi-works:
class subsubclass(subclass):
def __init__(self):
subclass.__init__(self)
self.subsubclassvar1 = self.subclassvar1
however the returned value is the original default value of subclass instead of the expected subclassedited.
I am not sure if I should even be trying to do this but I've got some code where the logic has now come to this point and I want to try see if I can get details from the middle class in to the final child class in their final modified states instead of the defaults and without refactoring a lot of code.
Each __init__ method should be invoking the parent's __init__ method, so that the instance is properly initialized for all the classes in the hierarchy.
class mainclass:
def __init__(self):
super().__init__()
self.mainclassvar1 = "mainclass"
class subclass(mainclass):
def __init__(self):
super().__init__()
self.subclassvar1 = "subclass"
def changeval(self):
self.subclassvar1 = "subclassedited"
class subsubclass(subclass):
def __init__(self):
super().__init__()
# Not sure why you would really need this, but...
self.subsubclassvar1 = self.subclassvar1
There's no reason, though that subsub.subclassvar1 should be related to sub.subclassvar1, though. Calling sub.changeval() has nothing to do with subsub.

Why does my code show NameError in python when I try to use of OOP and classes?

def God():
#code
class Human:
def __init__(self):
pass
class Man(Human):
def __init__(self):
pass
class Woman(Human):
def __init__(self):
pass
a=Man()
b=Woman()
return [a.__class__,b.__class__]
Why is this code showing NameError?
I am trying to create three classes and return the instances of two classes as an entities in an array
The test code is given below
paradise = God()
test.assert_equals(isinstance(paradise[0], Man) , True, "First object are a man")
Man and Woman are local variables inside the God() function, you can't reference them outside the function. You should take the class definitions out of the function.
And if you want to return instances, don't use __class__.
class Human:
def __init__(self):
pass
class Man(Human):
def __init__(self):
pass
class Woman(Human):
def __init__(self):
pass
def God():
a=Man()
b=Woman()
return [a ,b]

Can python's 'super' give child classes its parent classes class variables

I am trying to make it to where I can have multiple child classes from, for example class a, and I want all of the variables declared in class a's __init__ method to be in all of the child classes, while also not needing to enter any *args into the __init__ method.
My example parent class is:
class a:
def __init__(self):
self.t = 5
and my example child class is:
class c(a):
def __init__(self):
super().__init__()
does class c have the variable t from class a?
Would it be equal to 5?
While messing around with this, I get the error AttributeError: type object 'c' has no attribute 't', but shouldn't super().__init__() get the variable t from class a and make it to where class c has it too?
Yes, you're right, but the error occurs because you trying to access t on the class itself and not its instance. The following should work:
inst = c()
print(inst.t) # 5
class A:
def __init__(self):
self.a = 1
class B(A):
def __init__(self):
super().__init__()
self.b = self.a
print(self.b)
if __name__ == '__main__':
B()
Code example like this. You'll get 1 in command line. So just use self.attr.

Importing class variable python

I have two python classes, one uses the other's variable
class A:
class A(object):
variable = None
#classmethod
def init_variable(cls):
cls.variable = something
class B:
variable = __import__('module').A.variable
class B(object):
#staticmethod
def method():
return variable
I simplified my problem as much as possible. So my question is why I still have B.method() returning NoneType even if I update A.variable class variable with something using init_variable
I changed your code a bit so that it'd actually do what you want:
your_package/klass_A.py
class A(object):
variable = None
#classmethod
def init_variable(cls, something):
cls.variable = something
your_package/klass_B.py
from your_package.klass_A import A
class B(object):
#staticmethod
def method():
return A.variable
Now, you can actually update A.variable and use the updated variable in B as well. For example this:
print B.method()
A.init_variable('123')
print B.method()
returns:
None
123

Categories

Resources