class declaration shortcut

Luis M. González luismgz at gmail.com
Sat Mar 3 00:48:03 CET 2007


On Mar 2, 8:29 pm, "MonkeeSage" <MonkeeS... at gmail.com> wrote:
> On Feb 28, 1:26 pm, "Luis M. González" <luis... at gmail.com> wrote:
>
> > I've come across a code snippet inwww.rubyclr.comwhere 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


Thanks for your detailed reply!
So after all, the www.rubyclr.com code is not a fair comparison.
Because the c# code shows a class definition, and the ruby code shows
a struct definition, which is not equivalent to a class.
Is that right?




More information about the Python-list mailing list