Object's nesting scope
Bruno Desthuilliers
bruno.42.desthuilliers at websiteburo.invalid
Mon Aug 31 07:25:12 EDT 2009
zaur a écrit :
> On 28 авг, 16:07, Bruno Desthuilliers <bruno.
> 42.desthuilli... at websiteburo.invalid> wrote:
>> zaur a écrit :
>>
>>
>>
>>> On 26 авг, 17:13, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
>>>> Whom am we to judge? Sure if you propose this, you have some usecases in
>>>> mind - how about you present these
>>> 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?
Either 1/write an alternate initializer and bind it to the appropriate
classes or 2/write factory functions:
1/
from foreign_module import Person, Address
def my_init(self, **kw):
for k, v in kw.items():
setattr(self, k, v)
return self
Person.init = my_init
Address.init = my_init
person = Person().init(
name="john",
age=30,
address = Address().init(
street="Green Street",
no=12
)
)
2/
from functools import partial
import foreign_module
def my_factory(cls, **kw):
obj = cls()
for k, v in kw.items():
setattr(obj, k, v)
return obj
Person = partial(my_factory, foreign_module.Person)
Address = partial(my_factory, foreign_module.Address)
person = Person(
name="john",
age=30,
address = Address(
street="Green Street",
no=12
)
)
More information about the Python-list
mailing list