Feb-19-2019, 12:20 AM
(Feb-18-2019, 08:51 PM)PatM Wrote: If I write a class for others to use I have no control over how they use variable so from what I can tell I'm stuck writing self in front of every variable. Seems to go completely against the rest of the python philosophy on less typing to get things done.Has to use something to difference it from functions as all langues dos, it will work with
s
or this
,but self
is what we all know. There is a lot less typing in Python OOP even with
self

To give a example with some modern features like
super()
f-string
and a little older @property
,which all make it nicer.self
is only used when needed.class Foo: # No need for self on class attribute var = 'hello' count = 0 def __init__(self): self.age = 42 Foo.count += 1 class Bar(Foo): def __init__(self, name): super().__init__() self.name = name @property def future(self): # No need to us self as "year" only used in method year = 10 print(f'In {year} year i am {self.age + year}')Use:
>>> obj = Bar('Kent') >>> print(f'{obj.var} my name is {obj.name} age is {obj.age}') hello my name is Kent age is 42 >>> obj.count 1 >>> obj.future In 10 year i am 52 >>> obj = Bar('Tom') >>> obj.count 2