小编典典

如何在Python中模拟赋值运算符重载?

python

如何在Python中模拟赋值运算符重载?例如…

class Example(object):

    name = String()
    age = Integer()

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

除了执行self.name.value = name之外,还可以如何模拟赋值运算符的重载,以便在执行self.name =
myname时将myname分配给self.name.value?


阅读 454

收藏
2021-01-20

共1个答案

小编典典

我最终创建了一个名为ModelMeta的Model元类,该元类注册了类型化的属性。

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

在这种情况下,类型化的属性是图形数据库“属性”,它们都是Property类的所有子类。

参见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's primary index:
>>> nodes = g.people.index.lookup(name="James")

看到…

2021-01-20