class declaration shortcut

MonkeeSage MonkeeSage at gmail.com
Fri Mar 2 18:29:02 EST 2007


On Feb 28, 1:26 pm, "Luis M. González" <luis... at gmail.com> wrote:
> I've come across a code snippet in www.rubyclr.com where they show how
> easy it is to declare a class compared to equivalent code in c#.
> I wonder if there is any way to emulate this in Python.

I posted like 10 minutes ago, but it looks like it didn't go through.
The ruby code is not an easy way to declare a class, it is a ruby
class for creating c-like struct objects.

This is the basic idea behind the ruby Struct class (but this is quick
and dirty, the real implementation is different and done in c, but you
should get the basic idea):

class Struct2
    def initialize(*args)
        @@attrs = []
        args.each { |arg|
            eval("class << self; attr_accessor :#{arg} end")
            @@attrs.push(arg)
        }
    end
    def new(*args)
        args.each_index { |i|
            eval("self.#{@@attrs[i]}=args[i]")
            return self
        }
    end
end

Person = Struct2.new(:name)
bob = Person.new('bob')
puts bob.name


A python equiv. would be something like:

class Struct():
    def __init__(self, *args):
        self.attrs = []
        for arg in args:
            setattr(self, arg, None)
            self.attrs.append(arg)
    def __call__(self, *args):
        for i in range(len(args)):
            setattr(self, self.attrs[i], args[i])
        return self

Person = Struct('name')
bob = Person('bob')
print bob.name

Regards,
Jordan




More information about the Python-list mailing list