method to create class property

J

Joe P. Cool

Hi,

I like C#'s style of defining a property in one place. Can the
following way
to create a property be considered reasonable Python style (without
the
print statements, of course)?

class sample(object):
def __init__(self):
sample.y = self._property_y()

def _property_y(self):
def _get(self):
print 'getting y.'
return self._y
def _set(self, value):
print 'setting y.'
self._y = value
def _del(self):
print 'bye, y!'
del self._y
return property(_get, _set, _del)
 
D

Diez B. Roggisch

Joe said:
Hi,

I like C#'s style of defining a property in one place. Can the
following way
to create a property be considered reasonable Python style (without
the
print statements, of course)?

class sample(object):
def __init__(self):
sample.y = self._property_y()

def _property_y(self):
def _get(self):
print 'getting y.'
return self._y
def _set(self, value):
print 'setting y.'
self._y = value
def _del(self):
print 'bye, y!'
del self._y
return property(_get, _set, _del)



There are a few recipies, like this:


class Foo(object):

@apply
def foo():
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
return property(**locals())


Diez
 
J

Joe P. Cool

Joe said:
    def _property_y(self):
        def _get(self):
            [...]

There are a few recipies, like this:

class Foo(object):

     @apply
     def foo():
         def fget(self):
             return self._foo
         def fset(self, value):
             self._foo = value
         return property(**locals())

This is really cool! Thanks, Diez! I should definitely
learn to handle decorators :) But isnt't apply bound to
be dropped in Python 3.0?
 
D

Diez B. Roggisch

Joe said:
Joe said:
def _property_y(self):
def _get(self):
[...]
There are a few recipies, like this:

class Foo(object):

@apply
def foo():
def fget(self):
return self._foo
def fset(self, value):
self._foo = value
return property(**locals())

This is really cool! Thanks, Diez! I should definitely
learn to handle decorators :) But isnt't apply bound to
be dropped in Python 3.0?

In python 3.0, there will be an even nicer way - propset:


@property
def foo(self):
return self._foo

@propset
def foo(self, value):
self._value = value

Diez
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top