PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 26, 2022

[FIXED] How do I create a class method that adds a key to a global dictionary in python

 October 26, 2022     class, dictionary, methods, oop, python     No comments   

Issue

I am trying to build a database class in python, where i can add tables and rows and run other methods.

I'm facing an issue where when I add a table, it's not getting saved in the global dictionary. My code is as follows;

class DataBase():
    def __init__(self):
        self.data = {}
        
    def addTable(self, tableName):
        self.data[tableName] = {}

When I run that, then add a table and call on the dictionary, I still get an empty dict (as below)

tableName = "table"
DataBase().addTable(tableName)

DataBase().data

#output
{}

Can anyone help explain why this is?


Solution

Try the following code:

tableName = "table"
x = DataBase()
x.addTable(tableName)

The problem with your code is that when you did DataBase().addTable(tablename) what python did is initialize a new object because of DataBase() and added a table to it instead of the one you wanted it to add to.



Answered By - Matan Shalel
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing