简体   繁体   中英

Do each instance variable need a new property get/set method?

I've read several tutorials, articles and questions here on stackoverflow, including the python doc, but all of them are using a single instance variable in their examples, making it difficult to see how python properties would work if you have more than one.

At first i thought the property function was created to be able to set or get any property so you could only create one get and one set method and then any number of instance variables which would use these, but this doesnt seem to be the case(?)

If I have the following code (taken straight from the official doc on property()):

class C(object):
    def __init__(self):
        self._x = None

    def getx(self):
        return self._x
    def setx(self, value):
        self._x = value
    def delx(self):
        del self._x
    x = property(getx, setx, delx, "I'm the 'x' property.")

You have one method "getx" and one method "setx" in addition to the deleter method "delx". What if i also need a couple of more instances variables like y and z, do i then need to write the following code:

class C(object):
    def __init__(self, x, y, z):
        self._x = None
        self._y = 2
        self._z = 4

    def getx(self):
        return self._x
    def gety(self):
        return self._y
    def getz(self):
        return self._z

    def setx(self, value):
        self._x = value
    def sety(self, value):
        self._y = value
    def setz(self, value):
        self._z = value

    def delx(self):
        del self._x
    def dely(self):
        del self._y
    def delz(self):
        del self._z

    x = property(getx, setx, delx, "I'm the 'x' property.")
    y = property(gety, sety, dely, "I'm the 'y' property.")
    z = property(getz, setz, delz, "I'm the 'z' property.")

The above code looks a lot like java setters/getters, and the reason for using property in python seems to be exactly to avoid this, so are you meant to be using some sort og general getter/setter instead ?

Please dont bash me with tons of -1, im just trying to understand this and i have read quite a bit to try to avoid posting this people often get annoyed it seems when people arent a master in python.

The getters and setters in your example are useless, just skip them. All you need is:

class C(object):
    def __init__(self, x, y, z):
        self.x = None
        self.y = 2
        self.z = 4

Getters and setters are only needed if you want to do something unusual. Merely getting an attribute and setting an attribute can be done simply with an attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM