Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #197482

Re: Dynamic classes

From Mats Wichmann <mats@wichmann.us>
Newsgroups comp.lang.python
Subject Re: Dynamic classes
Date 2025-05-19 15:49 -0600
Message-ID <mailman.64.1747691398.3008.python-list@python.org> (permalink)
References <CAApdmf3UwA6zf2-eSfd=1U=Unx3-6PUj6+XS0Sp62rkn73C8iQ@mail.gmail.com> <385fb601-4061-4785-809a-94ee1e6c4e11@wichmann.us>

Show all headers | View raw


On 5/19/25 09:51, Jonathan Gossage via Python-list wrote:
> 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.

Might help if you show the init function. I've done something similar to 
this without trouble, but not using the unpacking (i.e. *args). I used 
this in an ancient blog post (thus, pre-typing, and such):

def transact(acct, amount):
     acct.balance += amount

def pay_interest(acct):
     acct.balance += acct.balance * acct.interest_rate

def account_init(acct, num, name, bal, rate):
     acct.acct_number = num
     acct.acct_holder = name
     acct.balance = bal
     acct.interest_rate = rate

account = {
     "acct_number": "XXX",
     "acct_holder": "",
     "balance": 0.0,
     "interest_rate": 0.0,
     "transact": transact,
     "pay_interest": pay_interest,
     "__init__": account_init,
}

AccountType = type("AccountType", (), account)

myaccount = AccountType("1234567", "J. Q. Public", 20.0, 0.01)
print(myaccount.balance)
myaccount.transact(-10)
print(myaccount.balance)
myaccount.pay_interest()
print(myaccount.balance)

Back to comp.lang.python | Previous | Next | Find similar


Thread

Re: Dynamic classes Mats Wichmann <mats@wichmann.us> - 2025-05-19 15:49 -0600

csiph-web