简体   繁体   English

为什么我的@property装饰器不起作用?

[英]Why aren't my @property decorators working?

I'm working on this little Class, playing with the @property decorators. 我正在研究这个小类,与@property装饰器一起玩。 For some reason it's not working right. 由于某种原因,它无法正常工作。

class Card:
    def __init__(self, rank, suit):
        self.rank = rank
        self.suit = suit

    @property 
    def rank(self):
        return self._rank

    @rank.setter
    def rank(self, value):
        valid_ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A"]
        if valid_ranks.index(value):
            self._rank = value

    @property
    def suit(self):
        return self._suit

    @suit.setter
    def suit(self,value):
        self._suit = value

    def show(self):
        print "{}{}".format(self.rank, self.suit)

I initialize an object like so: Card("cheese", "ball") , and presumably this should throw an error. 我像这样初始化一个对象: Card("cheese", "ball") ,并且大概应该抛出一个错误。 Python happily just rolls with it though and assigns "cheese" to rank. Python很高兴地随它一起滚动并分配“奶酪”排名。 What's going on here? 这里发生了什么? All other calls to the rank setter through assignment syntax seem to happily ignore the setter I've put in place. 通过赋值语法对等级设置器的所有其他调用似乎很高兴地忽略了我放置的设置器。 I'm running Python 2.7.5. 我正在运行Python 2.7.5。

You're using old-style classes. 您正在使用旧式类。 As noted in the documentation , properties don't work with old-style classes. 文档所述 ,属性不适用于旧式类。 Derive your classes from object . object派生您的类。 Eg: 例如:

class Card(object):
    ...

In Python 3 you don't need to do this, because Python 3 only has new-style classes. 在Python 3中,您不需要这样做,因为Python 3仅具有新型类。

You're initializing the rank and suit attributes without underscores but your property methods have _rank and _suit . 您正在初始化ranksuit属性,但不带下划线,但您的属性方法具有_rank_suit

Also list.index throws an error if an item is not in the list. 如果项目不在列表中,则list.index引发错误。 You should instead do 你应该做

if value in valid_ranks:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM