create a class with a dictionnary and one string as attributes in python

To create a class with a dictionary and a string as attributes, you can define the class as follows:

main.py
class MyClass:
    def __init__(self):
        self.my_dict = {}
        self.my_string = ""

94 chars
6 lines

In this code, we define a class called MyClass. The __init__ method is a special method in Python that is called when an instance of the class is created. We define two attributes of the class, my_dict and my_string.

my_dict is defined as an empty dictionary. You can add key-value pairs to this dictionary as needed.

my_string is defined as an empty string. You can assign a value to this string using the = operator.

Here's an example of how to use this class:

main.py
# create an instance of the class
my_class = MyClass()

# add values to the dictionary
my_class.my_dict["key1"] = "value1"
my_class.my_dict["key2"] = "value2"
my_class.my_dict["key3"] = "value3"

# assign a value to the string
my_class.my_string = "hello"

# print out the values of the attributes
print(my_class.my_dict)  # output: {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
print(my_class.my_string)  # output: hello
431 chars
15 lines

gistlibby LogSnag