[EDITED]
Take a look at this small experiment that explains my points
PS I was wondering why your code worked - here's why, you don't instantiate the class, you use it as is! Your
(Sep-14-2018, 10:05 AM)remy Wrote:This code is absolutely redundant - it creates class attributes with the same names as object attributes. It may cause a confusion and is a definite anti-pattern (not class attributes themselves, your usage). See the example belowclass Store: Day = 1 Money = 5 StoreName = "Lemonade Stand" StoreCount = 1 StoreCost = 3 StoreProfit = 1.5 StoreList = []
(Sep-14-2018, 10:05 AM)remy Wrote:Those are wrong cases forclass Store: @staticmethod def DisplayGameInfo(self): print("-----------------------------------") print("Day #" + str(self.Day)) print("Money = ${:0,.2f}".format(self.Money)) @staticmethod def DisplayStoreInfo(self): print("Store Name : %s, StoreCount = #%d " % (self.StoreName, self.StoreCount)) print("-----------------------------------")
staticmethod
decorator - those should be regular methods. Staticmethods in Python should not contain self
as a parameter - and should not address object/class attributes. The are just independent functions in the class namespace (and are seldom useful).Take a look at this small experiment that explains my points
Output:In [15]: class AntiPattern:
...: attr = 1
...: def __init__(self, attr):
...: self.attr = attr
...: @staticmethod
...: def show_attr(self):
...: return self.attr
...:
In [16]: a = AntiPattern(10)
In [17]: a.attr
Out[17]: 10
In [18]: AntiPattern.attr
Out[18]: 1
In [19]: a.show_attr()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-19-0d2c01c460f9> in <module>()
----> 1 a.show_attr()
TypeError: show_attr() missing 1 required positional argument: 'self'
The last - but not the least - your names are un-Pythonic, see PEP-8 for guidancePS I was wondering why your code worked - here's why, you don't instantiate the class, you use it as is! Your
__init__
method is never called. This is an absolutely wrong approach for OOP.
Test everything in a Python shell (iPython, Azure Notebook, etc.)
- Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
- Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
- You posted a claim that something you did not test works? Be prepared to eat your hat.