C
C
CrazyPanda2105102021-07-11 22:00:44
Python
CrazyPanda210510, 2021-07-11 22:00:44

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

2 answer(s)
L
longclaps, 2021-07-11
@CrazyPanda210510

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]

yes, somewhere in the giblets of the standard library, the list class is described, which has a reverse () method, but no shuffle () method. Therefore, you can refer to the former in the l.reverse() syntax, but not to the latter. But in another syntax, class.method(instance) you can refer to both! This, by the way, is due to the fact that the module is also a class, like many things in python, and the functions described in the module are module attributes.

A
Alexander, 2021-07-11
@sanya84

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 question

Ask a Question

731 491 924 answers to any question