A newbie question about class

Mark McEahern marklists at mceahern.com
Sat Feb 9 21:03:40 EST 2002


[newgene]
> Hi, group,
>      I have a newbie question about building a class:
>
> eg.
>
> class A:
>    def __init__(self,x=None):
>        self.x=x
>        if self.x != None:
>             self.y=x**2
>        else:
>             self.y=x**2

1.  When comparing to None, it's better to use one of the following:

	if x is not None:...
	if x is None:...

2.  Consider using property, which is new with Python 2.2 and requires a
new-style class (thus we subclass from object):

class A(object):

	def __init__(self, x=None):
		self._x = x

	def getX(self):
		return self._x

	def setX(self, x):
		self._x = x

	x = property(getX, setX)

a = A(1)
print a.x

Cheers,

// mark





More information about the Python-list mailing list