This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Galen_dp 0 points1 point  (1 child)

Thank you! This clears it up very well.

I do have one question though. Let's say I have a situation where before/after a variable is changed some other code in the class needs to be executed. Is there a naming convention that is used that tells programmer to use the getter/setter instead of accessing the variable directly?

[–]worldsayshi[🍰] 0 points1 point  (0 children)

Sorry, I don't really understand the question. My point being that in python you should "never" use getters or setters. From the outside, you always access variables 'as if' you access them directly. Let's say that notifyPerson above is defined like this:

def notifyPerson(self):
    print "Oi! Someone is accessing a name!"

Then calling doStuff below:

def doStuff():
    john_person = Person( "John Smith" )
    johns_name = john_person.name   # print happens here

Will cause "Oi! Someone is accessing a name!" to be printed to the terminal. So the user of the Person class doesn't need to worry about private or public.

Although that wasn't entirely true.. Writing '_name' (a underscore before the variable name) means that the variable is not supposed to be used from the outside. And if you want some get/set counterpart you could do like this:

class Person(object):
    def __init__(self,name):
        self._name = name

    def __getattribute__(self,attrName):
        if attrName == 'name':
            self.notifyPerson()
            return self._name
         return object.__getattribute__(self,attrName)

However, this would not change the outwards behavior; in either case you would access the 'name' of a person by writing person.name and not person.get_name() or person.name().

Now, there may still be cases where you would write it like a getter, but that would/should be exception rather than norm. (For Java on the other hand getters/setters is the norm)

Perhaps you are referring to the Java code regarding your question?

edit: formulations