I have a class:

class something(object):
    def __init__(self, name=None, someobjects=[]):
        self.name = name
        self.someobjects = someobjects

And I'd like to be able to get the number of those objects as a property or a method. e.g.

bob = something()
print bob.numberofojects
   5

or

bob.numberofobjects()
       5

I've tried adding the property to the class definition:

self.numberofobjects = len(someobjects)

or as a method in the class definition:

 def total(self):
     print len(self.someobjects)

But I haven't had success. Both attempts return 0 - (and the number is not 0) but the length for all the objects (for each item of this class) is a large number (the same number, but that's a different problem).

for person in listofpeoplewhoarethisclass:
        print person.name, person.numberofobjects, len(person.someobjects)

returns:

bob 0 716

for everyone....

有帮助吗?

解决方案

Use return instead of print in your total() function:

class something(object):
    def __init__(self, name=None, someobjects=[]):
        self.name = name
        self.someobjects = someobjects

    def total(self):
        return len(self.someobjects)

listofpeoplewhoarethisclass = [something("john", [1,2,3])]

for person in listofpeoplewhoarethisclass:
    print person.name, person.total(), len(person.someobjects)

returns: john 3 3

Hint: I don't know if you just named your class "something" or the list "listofpeoplewhoarethisclass" just for the question, but please give your classes, variables and lists useful and intuitive names (e.g. instead of "total" name the function "length" or "size", because total sound like a sum to me).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top