I really like to follow the standard coding style, but can't find an answer on this.
class Card:
"""Card class representing a playing card."""
RANKS = (None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9', '10',
'Jack', 'Queen', 'King')
SUITS = ('Clubs', 'Spades', 'Diamonds', 'Hearts')
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit
def __str__(self):
return f"{Card.RANKS[self.rank]} of {Card.SUITS[self.suit]}"
c = Card(1, 1)
print(c)
Should I write constants in class attributes all_lower_case or ALL_UPPER_CASE? PEP8 just says that constants should be ALL_UPPER_CASE at the module level. What about classes?
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)
In Python, constants are usually declared and assigned in a module. Here, the module is a new file containing variables, functions, etc which is imported to the main file. Inside the module, constants are written in all capital letters and underscores separating the words.
In proper python code, your class name should be capitalized. This helps to differentiate a class from a normal variable or function name.
Variables can only contain upper and lowercase letters (Python is case-sensitive) and _ (the underscore character). Hence, because we can't have spaces in variable names a common convention is to capitalize the first letter of every word after the first. For example, myName, or debtAmountWithInterest.
PEP8 makes it clear that constants should be upper-case:
Constants
Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL.
Note that it just says that these are usually defined on a module level. But if your values should be treated as constants then make them uppercase - even if they are defined on a class level.
Why not extract those outside of the class in the module like this:
from enum import Enum
class Suit(Enum):
CLUBS = 1
SPADES = 2
DIAMONDS = 3
HEARTS = 4
Then you could use it like:
Card(Rank.1, Suit.SPADES)
Also according to the following Python documentation it's ALL_CAPS, even inside Class. This also makes sense to me.
More info and examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With