python - 我很困惑,类 Card 对象不能手动设置但通过不同的类成功设置
问题描述
这是班级卡代码
class Card:
"class time definetion"
SUITS = ['Ace', 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Jack', 'Queen', 'King']
FACES = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
def __init__(self, face, suit):
self.face = face
self.suit = suit
@property
def face(self):
return self._face
@property
def suit(self):
return self._suit
@property
def image_name(self):
return str(self.suit).replace(' ', '_') + '.png'
def __repr__(self):
return f'Card(face="{self.face}", suit="{self.suit}")'
def __str__(self):
return f'{self.face} of {self.suit}'
def __format__(self, format):
return f'{str(self):{format}}'
但是当我试图创建一个类的对象时
w = Card(Card.FACES[1], Card.SUITS[1])
这是我得到的错误
AttributeError Traceback(最近一次调用最后一次)
在
----> 1 w = Card(Card.FACES[1], Card.SUITS[1])
in init(自我,脸,西装)
5
6 def __init__(self, face, suit):
----> 7 self.face = 脸
8 self.suit = suit
9
AttributeError:无法设置属性
然后我就好了,因为我只定义了getter而不是setter,但是为什么通过下面的类成功创建了对象而没有错误,因为该类还创建了Card对象这是第二个类代码
import random
from card import Card #to import the previous class
class DeckOfCards:
NUMBER_OF_CARDS = 52 # constant number of Cards
def __init__(self):
"""Initialize the deck."""
self._current_card = 0
self._deck = []
for count in range(DeckOfCards.NUMBER_OF_CARDS):
self._deck.append(Card(Card.FACES[count % 13],
Card.SUITS[count // 13]))
*如您所见,第二个类也生成 Card 对象,但我很困惑,如果没有前面的错误,这怎么可能???*
解决方案
你把你的属性名弄乱了一点,在你的__init__
, 你有self.face
和self.suit
作为属性,在你的类中,你还定义了具有相同名称和使用属性的 getter,并且self._face
在self._suit
你的 init 中没有定义。您可以通过将 init 更改为:
def __init__(self, face, suit):
self._face = face
self._suit = suit
可能您的其他方法也受到影响,我相信您可以自己修复它们。
推荐阅读
- c# - 如何在 C# 中拆分字符串数组的内容?
- mongodb - MongoDb 聚合,每个值的所有现有值
- java - 使用带有 RLO 的 redisson 本地缓存
- javascript - 如何为 lodash orderBy 的第二个参数指定两个值?
- php - 如何使用 PHP 缩短 URL
- spring - Spring boot Hibernate Schema 多租户动态租户
- angular - 发生未处理的异常:无法编译入口点@angular/material/tooltip
- go - VS Code: Go - main 在这个块中重新声明
- bash - 在 Cloud Run 上部署基于 bash 的服务器:如何修复 502 Bad gateway 错误?
- html - 即使内容更高的卡体,大小和宽度相同