我想了解内置函数的property工作原理.令我困惑的是,property它也可以用作装饰器,但它只在用作内置函数时才需要参数,而不是用作装饰器时.
这个例子来自文档:
class C(object):
def __init__(self):
self._x = None
def getx(self):
return self._x
def setx(self, value):
self._x = value
def delx(self):
del self._x
x = property(getx, setx, delx, "I'm the 'x' property.")
Run Code Online (Sandbox Code Playgroud)
property的论点是getx,setx,delx和文档字符串.
在下面的代码中property用作装饰器.它的对象是x函数,但在上面的代码中,参数中没有对象函数的位置.
class C(object):
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
Run Code Online (Sandbox Code Playgroud)
而且,如何在 …
python properties decorator python-internals python-decorators
我这样做:
def set_property(property,value):
def get_property(property):
Run Code Online (Sandbox Code Playgroud)
要么
object.property = value
value = object.property
Run Code Online (Sandbox Code Playgroud)
我是Python的新手,所以我还在探索语法,我想对此做一些建议.
我想序列化一个模型,但是想要包含一个额外的字段,该字段需要对要序列化的模型实例进行一些数据库查找:
class FooSerializer(serializers.ModelSerializer):
my_field = ... # result of some database queries on the input Foo object
class Meta:
model = Foo
fields = ('id', 'name', 'myfield')
Run Code Online (Sandbox Code Playgroud)
这样做的正确方法是什么?我看到你可以将额外的"上下文"传递给序列化器,是在上下文字典中传入附加字段的正确答案吗?使用这种方法,获得我需要的字段的逻辑不会与串行器定义一起自包含,这是理想的,因为每个序列化实例都需要my_field.在DRF序列化器文档的其他地方,它说 "额外的字段可以对应于模型上的任何属性或可调用".我正在谈论的是额外的领域吗?我应该在Foo模型定义中定义一个返回my_field值的函数吗?在序列化器中我将my_field挂钩到那个可调用的函数?那是什么样的?
在此先感谢,如有必要,请尽快澄清问题.
好的,这是我设置所有内容的代码:
if __name__ == '__main__':
app.debug = False
applogger = app.logger
file_handler = FileHandler("error.log")
file_handler.setLevel(logging.DEBUG)
applogger.setLevel(logging.DEBUG)
applogger.addHandler(file_handler)
app.run(host='0.0.0.0')
Run Code Online (Sandbox Code Playgroud)
会发生什么
我完全离开这里或者发生了什么事吗?
而不是每次我定义一个类时都编写这样的代码:
class Foo(object):
def __init__(self, a, b, c, d, e, f, g):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
self.g = g
Run Code Online (Sandbox Code Playgroud)
我可以使用此配方进行自动属性分配.
class Foo(object):
@autoassign
def __init__(self, a, b, c, d, e, f, g):
pass
Run Code Online (Sandbox Code Playgroud)
两个问题:
我使用Python作为OOP相当新.我来自Java背景.你会如何在python中编写一个javabean等价物?基本上,我需要一个类:
有什么投入?我正在寻找示例代码!
你怎么能扩展python属性?
子类可以通过在重载版本中调用它来扩展超类的函数,然后对结果进行操作.这是我说"扩展函数"时的一个例子:
# Extending a function (a tongue-in-cheek example)
class NormalMath(object):
def __init__(self, number):
self.number = number
def add_pi(self):
n = self.number
return n + 3.1415
class NewMath(object):
def add_pi(self):
# NewMath doesn't know how NormalMath added pi (and shouldn't need to).
# It just uses the result.
n = NormalMath.add_pi(self)
# In NewMath, fractions are considered too hard for our users.
# We therefore silently convert them to integers.
return int(n)
Run Code Online (Sandbox Code Playgroud)
是否有类似于扩展函数的操作,但对于使用属性装饰器的函数?
我想在获得昂贵的计算属性后立即进行一些额外的计算.我需要保持属性的访问权限.我不希望用户必须调用特殊例程来进行计算.基本上,我不希望用户知道首先进行的计算.但是,该属性必须保留属性,因为我需要支持遗留代码.
也许这是装饰师的工作?如果我没有弄错,decorator是一个包装另一个函数的函数,我想用一些更多的计算来包装一个属性,然后再将它作为一个属性呈现,这看起来像一个类似的想法......但是我无法弄明白.
我有一个基类LogFile,它具有昂贵的构造属性 …
我最近有一个令我困惑的问题,哪个是从外部检索属性的最佳方法.
假设我有一节课:
class Thing:
def __init__(self, whatever):
self.whatever = whatever
x = Thing('foo')
Run Code Online (Sandbox Code Playgroud)
现在我知道如果我想要检索whatever属性,我可以这样做:
x.whatever
Run Code Online (Sandbox Code Playgroud)
我有习惯(可能是因为我来自其他oo语言)来定义根据需要检索类属性的方法,并使用它们直接检索它们,例如:
class Thing:
def __init__(self, whatever):
self.whatever = whatever
def getWhatever(self):
return self.whatever
Run Code Online (Sandbox Code Playgroud)
在我的小经验中,我发现使用这种方法可以使事情在长期内变得更容易,因为如果我编辑数据属性的结构,我只需要编辑特定的方法.
但是因为我不是真正的蟒蛇老手,所以我很想知道我是不是做对了,或者其他一些方法是否更好,更py.思考?
class Employee:
def __init__(self, name):
self.name = name
def getName(self):
return self.name
@property
def getNameAgain(self):
return self.name
person = Employee("John")
print(person.getName()) #John <--(calling method)
print(person.name) #John <--(using @property)
Run Code Online (Sandbox Code Playgroud)
所以我使用 getName() 得到了相同的结果,那么为什么我们要在 getNameAgain() 中使用 @property 装饰器呢?我可以知道什么更好/建议使用吗?先感谢您!
在SQLAlchemy中,混合属性是应用于ORM映射类的属性或方法,
class Interval(Base):
__tablename__ = 'interval'
id = Column(Integer, primary_key=True)
start = Column(Integer, nullable=False)
end = Column(Integer, nullable=False)
def __init__(self, start, end):
self.start = start
self.end = end
@hybrid_property
def length(self):
return self.end - self.start
@hybrid_method
def contains(self,point):
return (self.start <= point) & (point < self.end)
@hybrid_method
def intersects(self, other):
return self.contains(other.start) | self.contains(other.end)
Run Code Online (Sandbox Code Playgroud)
这允许在类和实例级别执行不同的行为,从而使使用相同代码评估SQL语句变得更加简单,
>>> i1 = Interval(5, 10)
>>> i1.length
5
>>> print Session().query(Interval).filter(Interval.length > 10)
SELECT interval.id AS interval_id, interval.start AS …Run Code Online (Sandbox Code Playgroud) python ×9
decorator ×3
properties ×3
django ×2
attributes ×1
coding-style ×1
database ×1
extends ×1
flask ×1
inheritance ×1
java ×1
javabeans ×1
logging ×1
oop ×1
orm ×1
python-2.7 ×1
rest ×1
sqlalchemy ×1