[Tutor] Class Construction question
Magnus Lycka
magnus@thinkware.se
Mon Nov 11 20:22:01 2002
At 19:41 2002-11-11 -0500, Chris Davidson wrote:
>Here is the modified code:
>
>#!/usr/bin/python
>class Person:
> def __init__(Name):
> self.setPhone(Name)
> def setPhone(Name):
> self.PhoneNumber = string
> def setName(string):
> self.FirstName = string
> def getName():
> return self.FirstName
> def getPhoneNumber():
> return self.PhoneNumber
Which has at least half a dozen bugs... ;)
You have to be a bit more careful, or you will
have a lot of trouble getting anywhere. What
do you mean by:
def setPhone(Name):
self.PhoneNumber = string
???
Secondly, you must always use the instance itself
as the first parameter in methods. If
a = SomeClass()
Then
a.someMethod(x)
is just a short form of
SomeClass.someMethod(a, x)
Thirdly, a stylistic issue:
Your attribute names are certainly legal in Python,
but typically NamesLikeThis are used for classes
and namesLikeThis are used for attributes or
methods. There are good reasons to treat methods
and attributes the same, and it will be easier for
other python programmers to read your code and help
you if you follow the normal style.
Fourthly, it's a good idea to avoid shadowing standard
modules or built in function etc with local (or global)
variable names. aString is better than string as a
parameter name. (But something more descriptive lile
firstName is better yet.) If you later do "import string"
in your program and do something like:
def setName(self, string):
for char in string:
assert char in string.printable
self.firstName = string
you will get:
AttributeError: 'str' object has no attribute 'printable'
Since your local variable will "occupy" the name "string"
and make it difficult to reach the string module.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus@thinkware.se