Python属性不起作用

Sno*_*man 0 python google-app-engine

我有一个继承自ndb.Model(Google App Engine的东西)的对象.该对象有一个名为commentid的属性:

class Comment(ndb.Model):
   commentid = ndb.StringProperty()
Run Code Online (Sandbox Code Playgroud)

阅读一堆文章,他们都说这是实现财产的方式:

@property
def commentid(self):
   if not self._commentid:
       self._commentid = "1"
   return self._commentid
Run Code Online (Sandbox Code Playgroud)

但我得到一个错误说Comment object has no attribute _commentid.我究竟做错了什么?

编辑:好的,显然我在这里有点困惑.我来自Objective-C,如果你有一个属性,x那么你会自动获得一个_x在你的getter和setter中调用的变量.所以我认为这也是Python中发生的事情.但显然我需要使用下划线前缀手动设置变量的值.

我想要的只是实现一个getter,我会在返回之前检查一下这个值.我该怎么做?

小智 5

实现这样的属性需要您定义对象的属性.你在那里做的是定义一个名为Comment的类,但你没有为它的对象定义任何属性,你可以为类本身定义它们.

让我用一个小例子来证明:

class ExampleClass:
    name = "Example Object"

a = ExampleClass() # Init new instance of ExampleClass
print(a.name) # a doesn't own an attribute called "name"
print(ExampleClass.name) # --> "Example Object"
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我定义了class ExampleClass并给它一个name带有值的变量Example Object.之后,我创建了一个对象a = ExampleClass(),但它没有获取name属性,因为属性是为类本身定义的,而不是为它的对象定义的.

要解决此问题,请在__init__-method中定义名称,只要创建该类的对象,就会调用该名称.

class ExampleClass:
    def __init__(self):
        self.name = "Example Class"

a = ExampleClass() # Init new instance of ExampleClass
print(a.name) # --> "Example Class"
print(ExampleClass.name) # --> ERROR: Exampleclass.name doesn't exist
Run Code Online (Sandbox Code Playgroud)

我在那里ExampleClass再次定义,但我也__init__为它定义了方法.Init方法只接受一个参数,self该参数将自动赋予该函数.它是正在创建的对象.然后我设置self.name = "Example Class",因为self是对象本身,我们设置对象的属性name.

创建属性

要为属性实现setter和getter,请添加以下内容:

class ExampleClass:
    def __init__(self):
        self.name = "Example Class"

    @property
    def name(self):
        if not self._name:
            pass #blabla code here
        return self._name

    @name.setter
    def name(self, value):
        #blabla more code
        self._name = value
Run Code Online (Sandbox Code Playgroud)

此外,您还应该编辑__init__方法以name作为参数.

def __init__(self, name="Example Object"):
    self.name = name
Run Code Online (Sandbox Code Playgroud)