Skip to content

Instantly share code, notes, and snippets.

@PythonDotLand
Created June 29, 2021 07:47
Show Gist options
  • Select an option

  • Save PythonDotLand/6737ff43199abfecdc1dfe74c74a0115 to your computer and use it in GitHub Desktop.

Select an option

Save PythonDotLand/6737ff43199abfecdc1dfe74c74a0115 to your computer and use it in GitHub Desktop.
>>> class Card:
... __slots__ = 'rank', 'suite'
... def __init__(self, rank, suite):
... self.rank = rank
... self.suite = suite
...
>>> qh = Card('queen', 'hearts')
@AlkisPis
Copy link

AlkisPis commented Jul 2, 2021

I can't see how does using __slots__ = 'rank', 'suite' make for either faster writing or a cleaner code! Most probably it doesn't, otherwise you would have written en example. So, in fact, it makes for slower writing since one has to add this line! :)

@PythonDotLand
Copy link
Author

It's not about faster writing. It's about better performance and code safety. Most languages don't allow you to introduce new attributes to an object at will, for good reason. You can simulate this with slots.

@AlkisPis
Copy link

AlkisPis commented Jul 2, 2021

I saw this code in an article entitled "10 Advanced Python Tricks To Write Faster, Cleaner Code" (https://medium.com/pythonland) and this is were I referred to. (It is also there where I found the link https://python.land/ thet led me to write my comment.)
In fact, the above code was the first example and I was expecting to see something that will help me writing code faster because I am a relatively slow typist. But now you tell me it's not about faster writing ... Instead, you say that "it's about code safety". Well, the word "safety" is not mentioned even once. I really don't understand ... Anyway, forget about the whole issue, It's not wortwhile. But I hope at least that my message makes improve your articles.

@PythonDotLand
Copy link
Author

Well I see you apparently misinterpreted the title. It's about writing faster and cleaner code. If you want to type faster, I suggest a typing course ;)

@AlkisPis
Copy link

AlkisPis commented Jul 2, 2021

I see. You are right. It seems I am too preoccupied with the subject of writing faster, so I isolated that! :) In fact, for a moment I believed that this "solts" thing allows for not having to add the very stupid, annoying and time wasting 'self' prefix everytime to e.g. 'rank' and 'suite' ! :)) (I know well though that it is necessary and why, as in Java, with the corresp. prefix 'this'.)
Thanks and sorry about the trouble!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment