Re: Does python have the static function member like C++

2007-04-11 Thread goodwolf
On Apr 11, 5:19 am, 7stud [EMAIL PROTECTED] wrote:
 On Apr 10, 9:08 pm, 人言落日是天涯,望极天涯不见家 [EMAIL PROTECTED] wrote:

  I define the class like this:
  class AAA:
  counter = 0
  def __init__(self):
  pass
  def counter_increase():
  AAA.counter += 1
  print couter now :, AAA.counter

  But how could I call the function counter_incrrease ?

  Thanks !

 1)
 class AAA:
 counter = 0
 def __init__(self):
 pass
 @staticmethod
 def counter_increase():
 AAA.counter += 1
 print couter now :, AAA.counter

 AAA.counter_increase()

 2)
 class AAA:
 counter = 0
 def __init__(self):
 pass
 def counter_increase():
 AAA.counter += 1
 print couter now :, AAA.counter
 counter_increase = staticmethod(counter_increase)

 AAA.counter_increase()

 3)
 class AAA:
 counter = 0
 def __init__(self):
 pass
 def counter_increase(self):
 AAA.counter += 1
 print couter now :, AAA.counter
 aaa = AAA()
 AAA.counter_increase(aaa)

1. In this case you will prefer a classmethod instead a staticmethod.
2. If counter is the number of instances of class AAA then you will
incrase counter inside __init__ method.

class AAA (object):
counter = 0
def __init__(self):
type(self).counter_increase()
@classmethod
def counter_increase(cls):
cls.counter += 1

or

class AAA (object):
counter = 0
def __init__(self):
type(self).counter += 1

-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Does python have the static function member like C++

2007-04-11 Thread goodwolf
On Apr 11, 9:09 am, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 goodwolf a écrit :
 (snip)

  1. In this case you will prefer a classmethod instead a staticmethod.
  2. If counter is the number of instances of class AAA then you will
  incrase counter inside __init__ method.

  class AAA (object):
  counter = 0
  def __init__(self):
  type(self).counter_increase()

 You can call a class method on an instance:
 self.counter_increase()

 And FWIW, this is probably something I'd put in the constructor (the
 __new__ method), not in the initializer.

  @classmethod
  def counter_increase(cls):
  cls.counter += 1

  or

  class AAA (object):
  counter = 0
  def __init__(self):
  type(self).counter += 1

 Instances have a reference to their class, so you can also write this:
self.__class__.counter += 1

OK, you will use something like this:

class AAA (object):
counter = 0
def __new__(cls):
cls.counter += 1
return super(cls, cls).__new__(cls)

but I think that __new__ is more low level and not necessary here,
so I will use:

class AAA (object):
counter = 0
def __init__(self):
self.counter_increase()
@classmethod
def counter_increase(cls):
cls.counter += 1

with yours correction invoking self.counter_increase() instead of more
explicit type(self).counter_increase()

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Does python have the static function member like C++

2007-04-11 Thread goodwolf
On Apr 11, 10:15 am, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 goodwolf a écrit :



  On Apr 11, 9:09 am, Bruno Desthuilliers bruno.
  [EMAIL PROTECTED] wrote:
  goodwolf a écrit :
  (snip)

  1. In this case you will prefer a classmethod instead a staticmethod.
  2. If counter is the number of instances of class AAA then you will
  incrase counter inside __init__ method.
  class AAA (object):
  counter = 0
  def __init__(self):
  type(self).counter_increase()
  You can call a class method on an instance:
  self.counter_increase()

  And FWIW, this is probably something I'd put in the constructor (the
  __new__ method), not in the initializer.

  @classmethod
  def counter_increase(cls):
  cls.counter += 1
  or
  class AAA (object):
  counter = 0
  def __init__(self):
  type(self).counter += 1
  Instances have a reference to their class, so you can also write this:
 self.__class__.counter += 1

  OK, you will use something like this:

  class AAA (object):
  counter = 0
  def __new__(cls):
  cls.counter += 1
  return super(cls, cls).__new__(cls)

return super(AAA, cls).__new__(cls)

  but I think that __new__ is more low level and not necessary here,

 It's of course 'not necessary'. But (IMHO):
 - increasing the class's instance counter is more a responsability of
 the class than a responsability of the instance - and it has nothing to
 do with initializing the instance's state
 - if someone is to subclass AAA, there are fewer chances that he'll
 override the constructer than the initializer, and if he does, there are
 more chances that he won't forget to call on the parent's constructor.

 IOW, this is actually *because* it is 'lower level' that I think it's a
 better place for such operations.

 But YMMV, of course !-)

 My 2 cents...

OK, but then you will use an more flexible constructor:

class AAA (object):
counter = 0
def __new__(cls, *args, **kwargs):
cls.counter += 1
return super(AAA, cls).__new__(cls, *args, **kwargs)

then you see that you will pay lot resources for a lower level
operation.

However if your counter is to consider a low level think, than You are
right, but it's more a personal consideration.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class attrdict

2007-03-04 Thread goodwolf
On Mar 3, 4:25 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
 Hallvard B Furuseth [EMAIL PROTECTED] wrote:

  Does this class need anything more?
  Is there any risk of a lookup loop?
  Seems to work...

  class attrdict(dict):
  Dict where d['foo'] also can be accessed as d.foo
  def __init__(self, *args, **kwargs):
  self.__dict__ = self
  dict.__init__(self, *args, **kwargs)
  def __repr__(self):
  return dict.__repr__(self).join((attrdict(, )))

 The problem is mostly that, given an instance a of attrdict, whether you
 can call (e.g.) a.update(foo) depends on whether you ever set
 a['update'], making the whole program extremely fragile -- a very high
 price to pay for some modest amount of syntax sugar.

 Alex

Then you will prefer something like this:

class Namespace(object):
def __init__(self, __ns={}, **kwargs):
if kwargs: __ns.update(kwargs)
self.__dict__ = __ns

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class attrdict

2007-03-04 Thread goodwolf
On Mar 4, 1:03 pm, goodwolf [EMAIL PROTECTED] wrote:
 On Mar 3, 4:25 am, [EMAIL PROTECTED] (Alex Martelli) wrote:



  Hallvard B Furuseth [EMAIL PROTECTED] wrote:

   Does this class need anything more?
   Is there any risk of a lookup loop?
   Seems to work...

   class attrdict(dict):
   Dict where d['foo'] also can be accessed as d.foo
   def __init__(self, *args, **kwargs):
   self.__dict__ = self
   dict.__init__(self, *args, **kwargs)
   def __repr__(self):
   return dict.__repr__(self).join((attrdict(, )))

  The problem is mostly that, given an instance a of attrdict, whether you
  can call (e.g.) a.update(foo) depends on whether you ever set
  a['update'], making the whole program extremely fragile -- a very high
  price to pay for some modest amount of syntax sugar.

  Alex

 Then you will prefer something like this:

 class Namespace(object):
 def __init__(self, __ns={}, **kwargs):
 if kwargs: __ns.update(kwargs)
 self.__dict__ = __ns

oops, there is an error (empty dict is created once).
Here corrected one:

class Namespace(object):
def __init__(self, __ns=None, **kwargs):
if __ns is None:
self.__dict__ = kwargs
else:
assert len(kwargs) == 0
self.__dict__ = __ns

If you are familiar with JS then you can simulate JS Object:

class JSLikeObject(object):
def __init__(self, __ns={}, **kwargs):
if kwargs: __ns.update(kwargs)
self.__dict__ = __ns
def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __delitem__(self, name):
delattr(self, name)
def __iter__(self):
return iter(self.__dict__)
def __contains__(self, name):
return hasattr(self, name)

but I don't sagest to use it in real life.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class attrdict

2007-03-04 Thread goodwolf
class Namespace(object):
def __init__(self, __ns=None, **kwargs):
if __ns is None:#if no dictionary is given
self.__dict__ = kwargs  #then use kwargs without copying
or creating new dict
else:
assert len(kwargs) == 0
self.__dict__ = __ns#else use dictionary without
copyng

 #additional methods for JS like object (ONLY FOR DEMONSTRATION)
 def __getitem__(self, name):
return getattr(self, name)
def __setitem__(self, name, value):
setattr(self, name, value)
def __delitem__(self, name):
delattr(self, name)
def __iter__(self):
return iter(self.__dict__)
def __contains__(self, name):
return hasattr(self, name)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread goodwolf
On Feb 23, 5:12 pm, Steven W. Orr [EMAIL PROTECTED] wrote:
 I understand that two leading underscores in a class attribute make the
 attribute private. But I often see things that are coded up with one
 underscore. Unless I'm missing something, there's a idiom going on here.

 Why do people sometimes use one leading underscore?

 TIA

 --
 Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
 happened but none stranger than this. Does your driver's license say Organ ..0
 Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
 individuals! What if this weren't a hypothetical question?
 steveo at syslang.net

One underscore stay for 'protected'. Protected in OOP means that the
attribute is hidden outside the class but visible for subclasses. In
python one undersore is only a good convention for say that the
attribute is protected.
So users will ignore attributes with initial undersocre. Users who
subclass must know of that attributes existence for prevent unwonted
overriding.

Sory for my english.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Solved: Question about idiomatic use of _ and private stuff.

2007-02-23 Thread goodwolf
 If you say

 from foo import _fooa, _foob,

 then the import will fail because the _ is used only by the import to
 decide that you shouldn't see _fooa or _foob.

???

Read Python manuals, please.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a class name

2007-02-18 Thread goodwolf
On Feb 18, 9:17 am, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Sun, 18 Feb 2007 04:20:33 -0300, goodwolf [EMAIL PROTECTED]
 escribió:

  I suppose that you wont get class name into its code (or before
  definition end) but not into a method definition.

  import sys

  def getCodeName(deap=0):
  return sys._getframe(deap+1).f_code.co_name

  class MyClass (object):
  name = getCodeName() + '!'

 What's the advantage over MyClass.__name__?

 --
 Gabriel Genellina

 class C(object):
... name = C.__name__
...
Traceback (most recent call last):
  File stdin, line 1, in ?
  File stdin, line 2, in C
NameError: name 'C' is not defined


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help Required for Choosing Programming Language

2007-02-17 Thread goodwolf
In your situation consider C# too.
If you like python then try IronPython for .NET.
I think that C++ is not ideal for you.

P.S.: VB6 is NOT a real OOP language.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting a class name

2007-02-17 Thread goodwolf
I suppose that you wont get class name into its code (or before
definition end) but not into a method definition.


import sys

def getCodeName(deap=0):
return sys._getframe(deap+1).f_code.co_name


class MyClass (object):
name = getCodeName() + '!'


-- 
http://mail.python.org/mailman/listinfo/python-list


Re: output to console and to multiple files

2007-02-14 Thread goodwolf
like this?

class Writers (object):

def __init__(self, *writers):
self.writers = writers

def write(self, string):
for w in self.writers:
w.write(string)

def flush(self):
for w in self.writers:
w.flush():

import sys

logfile = open('log.txt', 'w')
sys.stdout = Writers(aya.stdout, file('log.out', 'w'), logfile)
sys.stderr = Writers(aya.stdout, file('log.err', 'w'), logfile)

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arguments of a function/metaclass

2007-01-16 Thread goodwolf

[EMAIL PROTECTED] je napisao/la:
 Hello,


 I have a member function with many (20) named arguments

 def __init__(self,a=1,b=2):
 self.a=a
 self.b=b

 I would like to get rid of the many redundant lines like self.a=a and
 set the members automatically.
 The list of default arguments could be given like

 def __init__(**kwargs):
 arglist={a:1,b:2]

 if this makes things easier

 Of course there has to be a check that raises an error in case of an
 unknown argument not mentioned in this list.


 I am sure there is an elegant way how to do this, could you give me any
 hints???


 Many thanks



 Daniel

A simply solution:

def __init__(self, a=1, b=2, c=3, ..):
for key, val in locals().items():
if key != 'self':
setattr(self.__class__, key, val)

in addition:

def set(self, **kwarg):
for key in kwargs:
if hasattr(self.__class__, key):
setattr(self.__class__, key, kwargs[key])
else:
raise 

This solution is appropriate with use of proprieties.
For better proprety usage look at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442418

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arguments of a function/metaclass

2007-01-16 Thread goodwolf

Gabriel Genellina je napisao/la:
 goodwolf [EMAIL PROTECTED] escribió en el mensaje
 news:[EMAIL PROTECTED]
  A simply solution:
 
  def __init__(self, a=1, b=2, c=3, ..):
 for key, val in locals().items():
 if key != 'self':
 setattr(self.__class__, key, val)
 
  in addition:
 
  def set(self, **kwarg):
 for key in kwargs:
 if hasattr(self.__class__, key):
 setattr(self.__class__, key, kwargs[key])
 else:
 raise 

 Why setattr(self.__class__,...) instead of setattr(self, ...)? You're
 modifying the class attributes, and that's not usually intended.

 -- 
 Gabriel Genellina

My error. Post was written directly. Sorry.

-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arguments of a function/metaclass

2007-01-16 Thread goodwolf

[EMAIL PROTECTED] je napisao/la:
 Hello,


 I have a member function with many (20) named arguments

 def __init__(self,a=1,b=2):
 self.a=a
 self.b=b

 I would like to get rid of the many redundant lines like self.a=a and
 set the members automatically.
 The list of default arguments could be given like

 def __init__(**kwargs):
 arglist={a:1,b:2]

 if this makes things easier

 Of course there has to be a check that raises an error in case of an
 unknown argument not mentioned in this list.


 I am sure there is an elegant way how to do this, could you give me any
 hints???


 Many thanks



 Daniel

def changeattrs(obj, __dict, **kwargs):
for name, value in __dict.iteritems():
if hasattr(obj, name):
setattr(obj, name, value)
else:
raise AttributeError
for name in kwargs:
if hasattr(obj, name):
setattr(obj, name, kwargs[name])
else:
raise AttributeError


def locals2self(depth=0):
import sys
ns = sys._getframe(depth+1).f_locals
obj = ns['self']
for name, value in ns.iteritems():
if name != 'self':
setattr(obj, name, value)





class C1(object):
def __init__(self, a=1, b=2, c=3, d=4):
locals2self()



class C2(object):
a = 1
b = 2
c = 3
d = 4

def __init__(self, **kwargs):
changeattrs(self, kwargs)

-- 
http://mail.python.org/mailman/listinfo/python-list