Path: csiph.com!fu-berlin.de!uni-berlin.de!not-for-mail From: ram@zedat.fu-berlin.de (Stefan Ram) Newsgroups: comp.lang.python Subject: Re: Dynamic classes Date: 19 May 2025 16:33:21 GMT Organization: Stefan Ram Lines: 58 Expires: 1 Jun 2026 11:59:58 GMT Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X-Trace: news.uni-berlin.de iyJmi116ZosBIuWomZPnOQ4n50PbXZrvyaPdRFQihsAHPd Cancel-Lock: sha1:kQuRzKUNDD926NpVFurgEY5NnOU= sha256:eUQmFnYa+9m36OCcI1b+nXpaXqnGFK/2xTY4G9Dn1/M= X-Copyright: (C) Copyright 2025 Stefan Ram. All rights reserved. Distribution through any means other than regular usenet channels is forbidden. It is forbidden to publish this article in the Web, to change URIs of this article into links, and to transfer the body without this notice, but quotations of parts in other Usenet posts are allowed. X-No-Archive: Yes Archive: no X-No-Archive-Readme: "X-No-Archive" is set, because this prevents some services to mirror the article in the web. But the article may be kept on a Usenet archive server with only NNTP access. X-No-Html: yes Content-Language: en-US Xref: csiph.com comp.lang.python:197481 Jonathan Gossage wrote or quoted: >I have created a dynamic class using the type() function: >x = type('MyFlags', (), {'Flag1': 1, 'Flag2': 2, 'Flag3: 4, ' '__init__' : >__init__}) >The new class is there, and the class variables, Flag1, Flag2, and Flag3, >are present correctly. However, when I try to create an instance of this >class with the following code: >y = x('Flag1', 'Flag2') >it fails with a TypeError stating that 'MyFlags' does not accept arguments. >What do I have to do to make this happen?. BTW __init__(self, *args) is >defined as the instance initializer. Excellent question! So, the reason you're getting that TypeError is your __init__ function isn't actually hooked up right when you build your class with "type". You got to set up your init before you call "type", and then drop it into the class dictionary as a /function/ (not as a string). Also, looks like you've got a typo in the Flag3 line - missing a quote. Here's how you want to do it: def __init__(self, *args): self.flags = args x = type( 'MyFlags', (), { 'Flag1': 1, 'Flag2': 2, 'Flag3': 4, '__init__': __init__ } ) y = x('Flag1', 'Flag2') print(y.flags) # Output: ('Flag1', 'Flag2') Basically, "type" needs the actual function object for "__init__", not just the name. If you mess that up or have a typo, Python just falls back on the default init, which doesn't take any arguments, and that's why you get the error. Here's the rundown: Problem: "__init__" isn't set up right Fix: Define "__init__" before calling "type" Problem: Typo in your dict Fix: Make sure it's 'Flag3': 4 Problem: Wrong reference Fix: Pass the function, not a string Once you clean that up, your class should take arguments just fine!