如何在Python中模拟赋值运算符重载? [英] How to Emulate Assignment Operator Overloading in Python?
问题描述
如何在Python中模拟赋值运算符重载?例如...
How can you emulate assignment operator overloading in Python? For example...
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?
Rather than doing self.name.value = name, how can you emulate overloading of the assignment operator so that myname is assigned to self.name.value when you do self.name = myname?
推荐答案
我最终创建了一个名为ModelMeta的模型元类,用于注册类型化属性.
I ended up creating a Model metaclass called ModelMeta that registers the typed attributes.
请参见 http://github.com/espeed/bulbs/blob /master/bulbs/model.py
在这种情况下,键入的属性是图形数据库属性",它们都是Property类的所有子类.
In this case, the typed attributes are graph-database "properties", 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's primary index:
>>> nodes = g.people.index.lookup(name="James")
看到...
- 灯泡模型API: http://bulbflow.com/docs/api/bulbs/model /
- 灯泡模型快速入门: http://bulbflow.com/quickstart/#models
- Bulbs Model API: http://bulbflow.com/docs/api/bulbs/model/
- Bulbs Model Quickstart: http://bulbflow.com/quickstart/#models
这篇关于如何在Python中模拟赋值运算符重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!