Answer the question
In order to leave comments, you need to log in
How to deal with classes in Python?
Newbie question.
I'm trying to figure out the classes and I can't understand in which cases it is necessary to add self, and when not. Why are values and suits called as an object, but deck in random.shuffle(deck) is not called as an object, but as a simple variable. I understand the meaning of self, but I can't figure out the rules of use.
help me please
import random
import Stack
class Acess:
values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8,
"9": 9, "10": 10, "J": 11, "Q": 12, "K": 13, "A": 14}
suits =("\u2660", "\u2666", "\u2663", "\u2665")
def create_suffed_deck(self):
deck = [(suit, value) for suit in self.suits for value in self.values]
random.shuffle(deck)
return deck
Answer the question
In order to leave comments, you need to log in
random.shuffle is defined in the random module and is not one of the list methods listed here . This is how it happened historically.
So, self usually occurs when you yourself create a class and its methods. When using the class self is not needed, that's it.
On the other hand, look: here is the list.reverse() method
l = [1, 2, 3]
l.reverse() # [3, 2 ,1]
this is very similar to what random.shuffle did, but now let's make it completely indistinguishable:l = [1, 2, 3]
list.reverse(l) # [3, 2 ,1]
As Mr. longclaps says, the list data type doesn't have a shuffle method, but that's an easy fix.
import random
class List(list):
def __init__(self, values=[]):
super().__init__(values)
def shuffle(self):
random.shuffle(self)
def main():
array = List([i for i in range(20)])
print(f"Массив как есть: {array}")
array.shuffle() # перетасовываем
print(f"Перемешанный массив {array}")
if __name__ == '__main__':
main()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question