A way to write properties

A

Arnaud Delobelle

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:
'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
3

I don't know why one would want to do this though :)
 
H

HEK

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:


Setting Test.x to 42>>> Test.x


'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


3

I don't know why one would want to do this though :)

Nice idea.
What would be the python2.7 version (adding __metaclass__=PropertyType
didn't help) ?
Many thanks
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top