Classes, attributes, objects and dictionaries in python

0

I have a question with the following code:

class Prueba():
    atributo = {}

p = Prueba()
p.atributo['a'] = 1

z = Prueba()
z.atributo
{'a':1}

How is it possible that by creating a new object, it has the dictionary that was assigned to the previous object?

    
asked by Samuel Guerra 16.11.2016 в 23:10
source

2 answers

2

You must differentiate what is known as "class attributes" and "attributes of an instance".

When you use the first code that you put, you are modifying that class attribute and, all the instances that you generate of that class will have the modifications that you have applied to it. In the event that you do something like this:

class Prueba():
    def __init__(self):
        self.atributo = {}

p = Prueba()
p.atributo['a'] = 1
print p.atributo

z = Prueba()
z.atributo
print z.atributo  

you will be modifying attribute in each of the instances that you generate. Getting what you wanted:

{'a': 1}
{}
    
answered by 16.11.2016 / 23:43
source
0

Here is a declaration of the class, what I do is initialize the attribute. I have taken this information from this page

class Prueba:
    def __init__(self):
        self.atributo = {}

p = Prueba()
p.atributo['a'] = 1
z = Prueba ()
print p.atributo['a']
print z.atributo['a']

This means as a result

1                                                                                                                                                                   
Traceback (most recent call last):                                                                                                                                  
  File "main.py", line 16, in <module>                                                                                                                              
    print z.atributo['a']

Executing the code in this page , which is used to execute Python Online code, and here another link to be able to analyze the Python code

    
answered by 16.11.2016 в 23:34