Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
newb selfie
#6
(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 Shifty if eg compare to Java/C++,i mean it's not couple of lines bot a lot more.

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
Reply


Messages In This Thread
newb selfie - by PatM - Feb-18-2019, 08:18 PM
RE: newb selfie - by micseydel - Feb-18-2019, 08:29 PM
RE: newb selfie - by Larz60+ - Feb-18-2019, 08:34 PM
RE: newb selfie - by PatM - Feb-18-2019, 08:51 PM
RE: newb selfie - by ichabod801 - Feb-18-2019, 10:07 PM
RE: newb selfie - by snippsat - Feb-19-2019, 12:20 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python newb need help Fictile 1 229 Apr-02-2024, 03:28 AM
Last Post: buran
  NameError issue with daughter's newb code MrGonk 2 1,462 Sep-16-2021, 01:29 PM
Last Post: BashBedlam
  Simple newb string question Involute 2 2,232 Sep-08-2019, 12:50 AM
Last Post: Involute
  please help this newb install pygame iofhua 7 5,969 May-15-2019, 01:09 PM
Last Post: buran
  Newb question: Debugging + Linting Python in Visual Studio Code Drone4four 1 2,443 Apr-15-2019, 06:19 AM
Last Post: perfringo
  Newb question about %02d %04d bennylava 30 19,660 Mar-05-2019, 11:23 PM
Last Post: snippsat
  Pthyon 3 question (newb) bennylava 11 5,931 Feb-28-2019, 06:04 PM
Last Post: buran
  Complete NEWB and openpyxl project Netopia 44 17,478 Jan-18-2019, 08:15 PM
Last Post: Netopia
  Newb Question - Threading in Crons vvarrior 2 2,804 Jul-20-2018, 08:12 PM
Last Post: vvarrior
  Matt's newb question 1 MattSS102 1 2,718 Aug-28-2017, 03:27 AM
Last Post: BerlingSwe

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020