473,785 Members | 2,425 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Proper class initialization

Usually, you initialize class variables like that:

class A:
sum = 45

But what is the proper way to initialize class variables if they are the
result of some computation or processing as in the following silly
example (representative for more:

class A:
sum = 0
for i in range(10):
sum += i

The problem is that this makes any auxiliary variables (like "i" in this
silly example) also class variables, which is not desired.

Of course, I could call a function external to the class

def calc_sum(n):
...

class A:
sum = calc_sum(10)

But I wonder whether it is possible to put all this init code into one
class initialization method, something like that:

class A:

@classmethod
def init_class(self ):
sum = 0
for i in range(10):
sum += i
self.sum = sum

init_class()

However, this does not work, I get
TypeError: 'classmethod' object is not callable

Is there another way to put an initialization method for the class A
somewhere *inside* the class A?

-- Christoph
Mar 1 '06 #1
12 7178
On Wed, Mar 01, 2006 at 09:25:36PM +0100, Christoph Zwerschke wrote:
Usually, you initialize class variables like that:

class A:
sum = 45

But what is the proper way to initialize class variables if they are the
result of some computation or processing as in the following silly
example (representative for more:

class A:
sum = 0
for i in range(10):
sum += i

The problem is that this makes any auxiliary variables (like "i" in this
silly example) also class variables, which is not desired.

Of course, I could call a function external to the class

def calc_sum(n):
...

class A:
sum = calc_sum(10)

But I wonder whether it is possible to put all this init code into one
class initialization method, something like that:
Yes, it is called a meta class.
class A:

@classmethod
def init_class(self ):
sum = 0
for i in range(10):
sum += i
self.sum = sum

init_class()

However, this does not work


What we normally think of as an instance is an instance of a class.
Classes are actually instances of metaclasses. What you are looking for
is __init__, but not the __init__ defined after 'class A...' you want
the __init__ that is called when you type 'class A....'

Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright" , "credits" or "license" for more information.
class MyMeta(type): .... def __init__(cls, *ignored):
.... cls.sum = 0
.... for (i) in range(10):
.... cls.sum += i
.... class A(object): .... __metaclass__ = MyMeta
.... print A.sum 45 print A.i Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'A' has no attribute 'i'


For something as simple as this example it is easier and cleaner
to move the loop into a function and do the one-liner assignment.
Because the metaclass can do _anything_ to the class the reader
is obliged to go read its code. The simple assignment from a
function obviously has no side effects.

Hope that helps,

-jackdied
Mar 1 '06 #2
Christoph Zwerschke wrote:
Usually, you initialize class variables like that:

class A:
sum = 45

But what is the proper way to initialize class variables if they are the
result of some computation or processing as in the following silly
example (representative for more:

class A:
sum = 0
for i in range(10):
sum += i

The problem is that this makes any auxiliary variables (like "i" in this
silly example) also class variables, which is not desired.

Of course, I could call a function external to the class

def calc_sum(n):
...

class A:
sum = calc_sum(10)

But I wonder whether it is possible to put all this init code into one
class initialization method, something like that:

class A:

@classmethod
def init_class(self ):
sum = 0
for i in range(10):
sum += i
self.sum = sum

init_class()

However, this does not work, I get
TypeError: 'classmethod' object is not callable

Is there another way to put an initialization method for the class A
somewhere *inside* the class A?

-- Christoph


Although I've never had the need for something like this,
this works:

class A:
sum=0
for i in range(10):
sum+=i
del i

or moving the initialization into __init__ method isn't
terribly inefficient unless are are creating LOTS of
instances of the same class.

class A:
def __init__(self):
self.sum=0
for i in range(10):
self.sum+=i
or you can do the do it before you instantiate the class

class A:
def __init__(self, initialvalue=No ne):
if initialvalue is not None: self.sum=initia lvalue
else: self.sum=0
for i in range(10):
sum+=i

b=A(sum)
c=A(sum)

-Larry Bates
Mar 1 '06 #3
Jack Diederich wrote:
... __metaclass__ = MyMeta


Thanks. I was not aware of the __metaclass__ attribute. Still a bit
complicated and as you said, difficult to read, as the other workarounds
already proposed. Anyway, this is probably not needed so often.

-- Christoph
Mar 1 '06 #4
Christoph Zwerschke wrote:
But I wonder whether it is possible to put all this init code into one
class initialization method, something like that:

class A:

@classmethod
def init_class(self ):
sum = 0
for i in range(10):
sum += i
self.sum = sum

init_class()


I don't run into this often, but when I do, I usually go Jack
Diederich's route::

class A(object):
class __metaclass__(t ype):
def __init__(cls, name, bases, classdict):
cls.sum = sum(xrange(10))

But you can also go something more akin to your route::

class A(object):
def _get_sum():
return sum(xrange(10))
sum = _get_sum()

Note that you don't need to declare _get_sum() as a classmethod, because
it's not actually a classmethod -- it's getting used before the class
yet exists. Just write it as a normal function and use it as such --
that is, no ``self`` or ``cls`` parameter.

STeVe
Mar 1 '06 #5
Steven Bethard wrote:
class A(object):
def _get_sum():
return sum(xrange(10))
sum = _get_sum()


What's wrong with sum = sum(xrange(10)) ?
Mar 2 '06 #6
Leif K-Brooks wrote:
Steven Bethard wrote:
class A(object):
def _get_sum():
return sum(xrange(10))
sum = _get_sum()


What's wrong with sum = sum(xrange(10)) ?


Nothing, except that it probably doesn't answer the OP's question. The
OP presented a "silly example":

class A:
sum = 0
for i in range(10):
sum += i

I assume the intention was to indicate that the initialization required
multiple statements. I just couldn't bring myself to write that
horrible for-loop when the sum() function is builtin. ;)

STeVe
Mar 2 '06 #7
Steven Bethard wrote:
I assume the intention was to indicate that the initialization required
multiple statements. I just couldn't bring myself to write that
horrible for-loop when the sum() function is builtin. ;)


Yes, this was just dummy code standing for something that really
requires multiple statements and auxiliary variables.

-- Christoph
Mar 2 '06 #8
Steven Bethard wrote:
I don't run into this often, but when I do, I usually go Jack
Diederich's route::

class A(object):
class __metaclass__(t ype):
def __init__(cls, name, bases, classdict):
cls.sum = sum(xrange(10))
Good idea, that is really nice and readable. Now all the init code is
defined inline at the top of the class definition.
But you can also go something more akin to your route::

class A(object):
def _get_sum():
return sum(xrange(10))
sum = _get_sum()

Note that you don't need to declare _get_sum() as a classmethod, because
it's not actually a classmethod -- it's getting used before the class
yet exists. Just write it as a normal function and use it as such --
that is, no ``self`` or ``cls`` parameter.


Often it's so simple ;-) But the disadvantage is then that you cannot
set the class variables directly inside that function. So if you have to
initialize several of them, you need to define several functions, or
return them as a tuple and it gets a bit ugly. In this case, the first
solution may be better.

-- Christoph
Mar 2 '06 #9
Steven Bethard wrote:
I don't run into this often, but when I do, I usually go Jack
Diederich's route::

class A(object):
class __metaclass__(t ype):
def __init__(cls, name, bases, classdict):
cls.sum = sum(xrange(10))


I think you should call the superclass __init__ as well:

class __metaclass__(t ype):
def __init__(cls, name, bases, classdict):
super(__metacla ss__, cls).__init__(n ame, bases, classdict)
cls.sum = sum(xrange(10))

Kent
Mar 2 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2520
by: brianobush | last post by:
# # My problem is that I want to create a # class, but the variables aren't known # all at once. So, I use a dictionary to # store the values in temporarily. # Then when I have a complete set, I want to # init a class from that dictionary. # However, I don't want to specify the # dictionary gets by hand # since it is error prone.
5
3566
by: Allen | last post by:
Hi all, I have a derived class that inherits from two base classes. One of the base class constructors takes as input a pointer that is initialized in the other base class. How can I make sure the base classes are properly initialized with the data they need when I call the derived class' constructor? -- Best wishes,
4
2196
by: Hunter Hou | last post by:
Folks, If a member variable is initialized in class, it must be static and const. I know this and regard it as a convention. But who knows why standard define this? What's the advangtage or otherwise shortcomings? For example, class C {
5
2385
by: silverburgh.meryl | last post by:
How come I an not use class initialization to initalize inherited attributes? i have this code: B::B(A& a) { x = a.x; y = a.y; } class A {
8
8932
by: Per Bull Holmen | last post by:
Hey Im new to c++, so bear with me. I'm used to other OO languages, where it is possible to have class-level initialization functions, that initialize the CLASS rather than an instance of it. Like, for instance the Objective-C method: +(void)initialize Which has the following characteristics: It is guaranteed to be run
5
2625
by: Dennis Jones | last post by:
Hello, I have a couple of classes that look something like this: class RecordBase { }; class RecordDerived : public RecordBase {
0
9646
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10096
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9956
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.