Class Encapsulation Errors in Python 2.3.3
Jeff Shannon
jeff at ccvcorp.com
Fri Nov 19 15:10:01 EST 2004
Tim Henderson wrote:
>Here is a partial implementation, i don't have the code with me but
>this is how the songs list is made
>
>code:
>-------------------------------------------
>class Album:
>
> name = ''
> songs = []
> artist = ''
>
> def __init__(self, name, artist):
>
> self.name = name
> self.artist = artist
>-------------------------------------------
>
>
Yes, this gives you class-level attributes, shared by all instances of
Album. In the case of name and artist, you're then creating
instance-level attributes ('self.name = name') which shadow the
class-level attribute. But you never bind 'songs' on the instance, so
you're just modifying the class-level (shared) songs list.
>after reading the code i came up with a possible solution:
>
>possible code:
>-------------------------------------------
>class Album:
>
> name = ''
> songs = False
> artist = ''
>
> def __init__(self, name, artist):
>
> self.name = name
> self.artist = artist
> if songs == False:
> songs = []
>------------------------------------------
>
>
That'll almost work -- within __init__(), you need to refer to songs as
self.songs (both times). But why bother with creating the class-level
attributes? If you just set them in __init__(), all will be fine.
class Album:
def __init__(self, name, artist):
self.name = name
self.artist = artist
self.songs = []
will have the same net effect as your code, for the vast majority of
common purposes. (There are corner cases where having class-level
defaults is helpful, but I sincerely doubt that this is true for your
program.)
Jeff Shannon
Technician/Programmer
Credit International
More information about the Python-list
mailing list