En Fri, 28 Aug 2009 15:25:55 -0300, zaur <szp...@gmail.com> escribió:
On 28 авг, 16:07, Bruno Desthuilliers <bruno.
42.desthuilli...@websiteburo.invalid> wrote:
zaur a écrit :

> Ok. Here is a use case: object initialization.

> For example,

> person = Person():
>   name = "john"
>   age = 30
>   address = Address():
>      street = "Green Street"
>      no = 12

> vs.

> person = Person()
> person.name = "john"
> person.age = 30
> address = person.address = Address()
> address.street = "Green Street"
> address.no = 12

Err... Looks like you really should read the FineManual(tm) -
specifically, the parts on the __init__ method.

class Person(object):
    def __init__(self, name, age, address):
        self.name = name
        self.age = age
        self.address = address

class Address(object):
    def __init__(self, street, no):
        self.no = no
        self.street = street

person = Person(
    name="john",
    age=30,
    address = Address(
        street="Green Street",
        no=12
    )
)

What are you doing if 1) classes Person and Address imported from
foreign module 2) __init__ method is not defined as you want?

Welcome to dynamic languages! It doesn't matter *where* the class was defined. You may add new attributes to the instance (even methods to the class) at any time.

1)
person = Person()
vars(person).update(name="john",age=30,address=Address())
vars(person.Address).update(street="Green Street",no=12)

2)
def the_initializer_i_would_like(person, name, age):
  person.name = name
  person.age = age

person = Person()
the_initializer_i_would_like(person, name="john", age=30)

3)
def the_initializer_i_would_like(self, name, age):
  self.name = name
  self.age = age

Person.init = the_initializer_i_would_like
person = Person()
person.init(name="john", age=30)

4)
def a_generic_updater(obj, **kw):
  try: ns = vars(obj)
  except Exception: ns = None
  if ns is not None:
    ns.update(kw)
  else:
    for name in kw:
      setattr(obj, name, kw[name])

person = Person()
a_generic_updater(person, name="john", age=30)

--
Gabriel Genellina

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

Reply via email to