I wonder if while working with OPP/Classes/Instances in Python I should be always using getAttr()/setAttr() when reading-writing from-to a Class's attribute/variable. Or dealing with the variable/attribute directly (such as self.my_attr = "some_value") would be a better practice?

Direct access to Class attr

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()
        self.my_attr = 'My_Value'

    def doSomething(self):
        localVariable = self.my_attr
        print localVariable

Using a Class's method to access a Class's attr

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()
        self.my_attr = 'My_Value'

    def getMyAttr(self):
        return self.my_attr

    def doSomething(self):
        localVariable = self.my_attr
        print localVariable

EDITED LATER:

While reading 'The Object-Oriented Thought Process' book (Matt Weisfeld : Developer's Library) ... The author states continuously throughout it:

"...Access to attributes within an object should be controlled by the object itself—no other object should directly change an attribute of another..."

"...If you control the access to the attribute, when a problem arises, you do not have to worry about tracking down every piece of code that might have changed the attribute—it can only be changed in one place (the setter)..."

I will be sticking to setters and getters then. Suggested/mentioned here Python's @property and @.setter make it even easier.

有帮助吗?

解决方案 2

Instead of the latter example, consider using the @property decorator.

class MyClass(object):
    def __init__(self):
        super(MyClass, self).__init__()
        self.__my_attr = 'My_Value'

    @property
    def my_attr(self):
        return self.__my_attr

    def doSomething(self):
        localVariable = self.__my_attr
        print localVariable

Use it only if you have good reason to protect the member, e.g. if you want to validate its values:

class Person:
    @property
    def age(self): return self.__age

    @age.setter
    def age(self, value):
        if value < 0: raise Exception('Age out of bounds.')
        self.__age = value

p = Person ()
p.age = 14
print (p.age)
p.age = -34

其他提示

You should access the variable directly.

If you subsequently need to add some logic for getting/setting the value, convert it to a property.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top