[Python-ideas] C# style properties
Christian Heimes
lists at cheimes.de
Thu Jul 12 17:43:25 CEST 2007
Hello!
In the past few months I've been toying around with .NET, C# and
PythonNet. While I still think that C# is too wory (public static
explicit operator Egg(Spam spam) { ... }) C# has one syntax feature I
really like to see in Python.
private float _a
public float a
{
get { return _a; }
set { _a = value; }
}
I think it's a very nice way to define a variable that acts similar to
Python properties. get, set and value are part of the syntax.
Python has no nice way to define a property with set and get. You always
have to use lambda or some private methods.
class Now:
_a = 0.0
@property
def a(self):
"""Read only property
return self._a
def _geta(self):
return self._a
def _seta(self, value):
self._a = value
a = property(_geta, _seta)
It puts a lot of methods into the body of the class that are only used
for properties. I find the C# syntax more intriguing. It puts the getter
and setter into a block of their own and makes reading and understand
the property more easy.
What do you think about this syntax?
class EasyExample:
_a = 0.0
property a:
"""doc string
"""
def get(self) -> float:
return self._a
def set(self, value):
self._a = float(value)
def delete(self):
del self._a
It may be possible to combine the feature with generic methods but I
guess that's not going to be easy.
class ComplexExample:
_a = 0.0
property a:
"""doc string
"""
def get(self) -> float:
return self._a
@generic
def set(self, value:float):
self._a = value
@generic
def set(self, value:int):
self._a = float(value)
@generic
def set(self, value:str):
self._a = float(value)
def delete(self):
del self._a
An alternative syntax. It doesn't look as clean as the other syntax but
has the benefit that the variable is in front of the definition.
class AlternativeSyntax:
_a = 0.0
a = property:
"""doc string
"""
Comments?
Christian
More information about the Python-ideas
mailing list