How to emulate target operator overload in Python?

How can you emulate target operator overloading in Python? For instance...

class Example(object):

    name = String()
    age = Integer()

    def __init__(self,myname,myage):
        self.name.value = myname
        self.age.value = myage

Instead of doing self.name.value = name, how can you emulate an overload of an assignment operator so that myname is assigned to self.name.value when you do self.name = myname?

+3
source share
4 answers

I ended up creating a Model metaclass called ModelMeta that registers typed attributes.

See http://github.com/espeed/bulbs/blob/master/bulbs/model.py

In this case, typed attributes are the "properties" of the graph database, which are all subclasses of the Property class.

. https://github.com/espeed/bulbs/blob/master/bulbs/property.py

:

# people.py

from bulbs.model import Node, Relationship
from bulbs.property import String, Integer, DateTime
from bulbs.utils import current_datetime

class Person(Node):

    element_type = "person"

    name = String(nullable=False)
    age = Integer()


class Knows(Relationship):

    label = "knows"

    created = DateTime(default=current_datetime, nullable=False)

:

>>> from people import Person
>>> from bulbs.neo4jserver import Graph
>>> g = Graph()

# Add a "people" proxy to the Graph object for the Person model:
>>> g.add_proxy("people", Person)

# Use it to create a Person node, which also saves it in the database:
>>> james = g.people.create(name="James")
>>> james.eid
3
>>> james.name
'James'

# Get the node (again) from the database by its element ID:
>>> james = g.people.get(james.eid)

# Update the node and save it in the database:
>>> james.age = 34
>>> james.save()

# Lookup people using the Person model primary index:
>>> nodes = g.people.index.lookup(name="James")

...

0

descriptor. , , , , Integer String .

premade, - property(). :

>>> class Foo(object):
        @property
        def bar(self):
            print 'bar'
            return 'bar'
        @bar.setter
        def bar(self, value):
            print 'bar =', value


>>> afoo = Foo()
>>> afoo.bar
bar
'bar'
>>> afoo.bar = 'baz'
bar = baz
>>> 
+13

python, , A <= B + C, rshift, . this.

+2

. . .

class Example(object):

    def __init__(self,myname, myage):
        self.name = String(myname)
        self.age = Integer(myage)

, str int.

0

Source: https://habr.com/ru/post/1540515/


All Articles