0

I have a class (say called Account) saved a as a variable (say cur_class) and I want to initialize an instance of the class. I thought

cur_class.__init__() 

would work but it is giving me 'unbound method init() must be called with Account instance as first argument (got nothing instead)'. Obviously I'm doing something wrong - can anyone point me in the right direction?

Thanks, Richard

6
  • 2
    Why do this? It's done automatically when you do our_class(). Commented May 25, 2011 at 14:13
  • @S.Lott - I'm not big on python and didn't realise you could simply add some brackets after a variable name to instantiate. It's not that common in langauges. Commented May 25, 2011 at 14:14
  • 2
    @Richard: "It's not that common in langauges" Please don't assume things and impose other language syntax on Python. It will lead to more confusion and more strange and difficult to answer questions. A tutorial will save you a lot of time. Commented May 25, 2011 at 14:18
  • 1
    @S.Lott - I don't think the question was strange or difficult to answer. I'd searched through python documentation for about half an hour before asking this. If you have any good tutorials, please feel free to recommend. Commented May 25, 2011 at 14:21
  • 1
    @Richard, note that you should probably call it CurClass, as Python naming convention says that cur_class (lower case with underscores) should be used for variable names. Commented May 25, 2011 at 14:51

1 Answer 1

6

Try cur_class(). For example:

In [1]: class C(object): pass
   ...: 

In [2]: cur_class = C

In [3]: obj = cur_class()

In [4]: obj
Out[4]: <__main__.C object at 0x1953c50>

A slightly longer explanation is that Python classes are callable. Calling a class returns a new instance.

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.