I've followed a tutorial where a Person class was used to illustrate the difference between class and instance variables. Something like:
class Person(object):
population=0
def __init__(self, name):
self.name=name
Person.population += 1
print 'current population', Person.population
Sally=Person('sally')
Joe=Person('joe')
This example really illustrated the difference between class and instance variables to me; however, it also really confuses me. When I think about it, the Person class is holding the attributes for an individual. The concept of a population; however, is a group of people. Therefore, it seems natural in OOP that a container class, "People" would store the variable population. When you really think about it, "People" is a composition of "Person" objects. And furthermore, the population itself is not really an independent variable. Instead, it is a property of the real variable, which is a list of "Person" objects. Let me show you what I mean:
class Person(object):
def __init__(self, name):
self.name=name
print 'Instantiating person', name
class People(object):
def __init__(self, persons):
self.persons=persons
def add_member(self, person):
print 'adding a crew member', person.name
self.persons.append(person)
def getpop(self):
print 'my population is now', len(self.persons)
return len(self.persons)
population=property(getpop)
sally=Person('sally')
joe=Person('joe')
crew=People([sally, joe])
print crew.population, 'is the new population'
bob=Person('bobby')
crew.add_member(bob)
print crew.population, 'is the new population'
I would argue that my People class is a more canonical way of representing a population of people because it holds a list of people and the population is merely a property of this list (i.e. the length of the list).
Let me ask 2 questions. First and simply, how do I implement an interface for Person in my People class so that People knows to expect a list of Person objects and not just any old python list. Aka, I can't pass the following:
crew=People([32, 'not a Person object, just a string here'])
Second, do you think that what I'm saying makes sense, or is there a better/preferred/standard way to do this without relying on properties and/or class composition? Are there recommended ways to build such container classes?