0

I have this problem while making my simple make_class. Here is my code:

def make_class(attrs, class_name, base=None):
    def get(name):
        if name in attrs:
            return attrs[name]
        elif base:
            return base['get'](name)

    def set(name, value):
        attrs[name] = value

    return cls

Running the program -

def make_user():
    return make_class('Test', {'code': 0.202})


def make_user_class():
    def init(self, owner):
        self['set']('name', owner)
        self['set']('number1', 0)

    return make_class(Test, 'TUser', {'__init__': init, 'code': 0.03})


Test = make_user()
TAccount = make_user_class()
Test['get']('name')

I tried to set the value in the def set(name, value): function but then it says

Traceback (most recent call last): File "main.py", line 276, in Test = make_user() File "main.py", line 265, in make_user return make_class('TAccount', {'interest': 0.202}) File "main.py", line 259, in make_class cls['set']('class_name', class_name) File "main.py", line 232, in set attrs[name] = value TypeError: 'str' object does not support item assignment

10
  • 2
    Your code is indented incorrectly. Please edit your question. Also see minimal reproducible example. Commented Jan 5, 2021 at 12:47
  • 1
    can you make a minimal reproducible example of your error? also, post the whole error message Commented Jan 5, 2021 at 12:47
  • 1
    @oskros Indeed, I just don't want to edit the question, if that is what the mistake is. Commented Jan 5, 2021 at 12:48
  • 2
    What is supposed to be the purpose of this code? Commented Jan 5, 2021 at 12:51
  • 1
    Also, please edit your question to provide the full error traceback, the current output, and the expected output. Commented Jan 5, 2021 at 12:55

1 Answer 1

1

Here is the signature you used to define make_class:

def make_class(attrs, class_name, base=None):

When you call make_class, the positional arguments need to be in the correct order:

def make_user():
    return make_class({'code': 0.202}, 'Test')


def make_user_class():
    def init(self, owner):
        self['set']('name', owner)
        self['set']('number1', 0)

    return make_class({'__init__': init, 'code': 0.03}, 'TUser', Test)

Note that having make_user_class refer to a predefined global Test probably isn't a great idea. make_user_class itself should probably take the desired base class as an argument itself:

def make_user_class(base):
    def init(self, owner):
        self['set']('name', owner)
        self['set']('number1', 0)

    return make_class({'__init__': init, 'code': 0.03}, 'TUser', base)


Test = make_user()
TAccount = make_user_class(Test)
Test['get']('name')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.