0 votes
1 view
in Python by (11.5k points)

 Here is a pure Python-specific design question:

class MyClass(object):

...

def get_my_attr(self):

...

def set_my_attr(self, value):

...

       

   and

class MyClass(object):

...

@property

def my_attr(self):

...

@my_attr.setter

def my_attr(self, value):

...

Python lets us do it either way. If you would design a Python program, which approach would you use and why?

1 Answer

0 votes
by (107k points)

If you are using properties it lets you begin with normal attribute accesses and then it back them up with getters and setters if necessary. So in short properties wins.

Sometimes we need for getters and setters, but even then, we can try other approaches and  "hide" them. There are many ways to do this in Python like (getattr, setattr, __getattribute__, etc).

But a very concise way is to use the following:

def set_address(self, value): 

if '@' not in value: 

     raise Exception("This doesn't look like an address") self._address = value

def get_address(self):

     return self._address 

address = property(get_address, set_address)

Related questions

0 votes
1 answer
+1 vote
1 answer
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...