Re: A way to write properties

2012-01-24 Thread HEK
On Jan 23, 12:45 pm, Arnaud Delobelle  wrote:
> Hi all,
>
> It just occurred to me that there's a very simple but slightly
> different way to implement properties:
>
> class PropertyType(type):
>     def __get__(self, obj, objtype):
>         return self if obj is None else self.get(obj)
>     def __set__(self, obj, val):
>         self.set(obj, val)
>     def __delete__(self, obj):
>         self.delete(obj)
>
> class Property(metaclass=PropertyType):
>     pass
>
> # Here is an example:
>
> class Test:
>     class x(Property):
>         "My property"
>         def get(self):
>             return "Test.x"
>         def set(self, val):
>             print("Setting Test.x to", val)
>
> # This gives:
>
> >>> t = Test()
> >>> t.x
> 'Test.x'
> >>> t.x = 42
>
> Setting Test.x to 42>>> Test.x
> 
> >>> Test.x.__doc__
>
> 'My property'
>
> It also allows defining properties outside class scopes:
>
> class XPlus1(Property):
>     "My X Property + 1"
>     def get(self):
>         return self.x + 1
>     def set(self, val):
>         self.x = val - 1
>
> class A:
>     def __init__(self):
>         self.x = 0
>     x_plus_one = XPlus1
>
> class B:
>     def __init__(self):
>         self.x = 2
>     x_plus_one = XPlus1
>
> >>> a = A()
> >>> b = B()
> >>> a.x
> 0
> >>> a.x_plus_one
> 1
> >>> b.x_plus_one
>
> 3
>
> I don't know why one would want to do this though :)
>
> --
> Arnaud

Nice idea.
What would be the python2.7 version (adding __metaclass__=PropertyType
didn't help) ?
Many thanks
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonic way of saying 'at least one of a, b, or c is in some_list'

2010-10-29 Thread HEK
On Oct 28, 6:16 pm, "cbr...@cbrownsystems.com"
 wrote:
> It's clear but tedious to write:
>
> if 'monday" in days_off or "tuesday" in days_off:
>     doSomething
>
> I currently am tending to write:
>
> if any([d for d in ['monday', 'tuesday'] if d in days_off]):
>     doSomething
>
> Is there a better pythonic idiom for this situation?
>
> Cheers - Chas

The most pythonic way is the following:

class anyof(set):
def __contains__(self,item):
if isinstance(item,anyof):
for it in item:
if self.__contains__(it):
return True
else:
return False
return super(anyof,self).__contains__(item)

daysoff=anyof(['Saterday','Sunday'])
assert anyof(['monday','tuesday']) in daysoff

best regards
Hassan
-- 
http://mail.python.org/mailman/listinfo/python-list