I have to prgrams and thus, two question to ask. In the following program how does the line status = staticmethod(status) do anything? My python programming book somehow connects it to the line Critter.total += 1 but I don't see how? Please explain.

# Classy Critter
# Demonstrates class attributes and static methods

class Critter(object):
    """A virtual pet"""
    total = 0
    
    
    def status():
        print "\nThe total number of critters is", Critter.total
        
    status = staticmethod(status)
        
    def __init__(self, name):
        print "A critter has been born!"
            
        self.name = name
            
        Critter.total += 1
            
            
# main

print "Accessing the class attribute Critter.total:",
print Critter.total

print "\nCreating critters."

crit1 = Critter("critter 1")
crit2 = Critter("critter 2")
crit3 = Critter("critter 3")

Critter.status()

print "\nAccessing the class attribute through an object:",
print crit1.total

raw_input("\n\nPress the enter key to exit.")

The second program I want to know, does the self line self.__mood in the talk method refer to self in the talk method itself? Or the __init__ method where __mood was created. The same question goes for self.__private_method(). Does the self refer to the self in public_method where it was called, or again, the __init__ method/constructor?

# Private Critter
# Demonstrates private variables and methods

class Critter(object):
    """A virtual pet"""
    def __init__(self, name, mood):
        print "A new critter has been born!"
        
        self.name = name        # public attribute
        self.__mood = mood      # private attribute
        
        
    def talk(self):
        print "\nI'm", self.name
        print "Right now I feel", self.__mood, "\n"
        
    
    def __private_method(self):
        print "This is a private method."
        
    def public_method(self):
        print "This is a public method."
        
        self.__private_method()
        
# main

crit = Critter(name = "Poochie", mood = "happy")

crit.talk()
crit.public_method()

raw_input("\n\nPress the enter key to exit.")

Recommended Answers

All 5 Replies

Well for your first queston I found this that might make things a bit more clear for you. http://code.activestate.com/recipes/52304/
As for your secound question. And I hope I'm not way off in left feild about this. But I believe they are trying to domonstrate that some attributes and methods are accessible from outside the class "public", and that the others are only accessible from inside the class itself "private". I didn't test that, I'm kinda making a large assumption by just glancing at the code.

Well for your first queston I found this that might make things a bit more clear for you. http://code.activestate.com/recipes/52304/
As for your secound question. And I hope I'm not way off in left feild about this. But I believe they are trying to domonstrate that some attributes and methods are accessible from outside the class "public", and that the others are only accessible from inside the class itself "private". I didn't test that, I'm kinda making a large assumption by just glancing at the code.

Yes that is correct, but it doesn't answer the question I had about self being use in this case.

Member Avatar for masterofpuppets

ok I'll try my best to explain what's goig on here :) sorry if it doesn't work out any good :)

for your first question:
I've never used the staticmethod function before but I ran the code and I think it changes the type of the argument method, in this case status, to static. This means that you can call the method without using an instance of the class, in this case Critter. And that's exactly what the code does, i.e it calls status via the class name rather than an instance variable for the class - Critter.status().
Now if you remove or comment the statement status = staticmethod( status ) and run the code, you'll get an error like:

Traceback (most recent call last):
  File "C:/Documents and Settings/jori/Desktop/t.py", line 27, in <module>
    Critter.status()
TypeError: unbound method status() must be called with Critter instance as first argument (got nothing instead)

And this is because status is an unbound method and you need to put self as a parameter like this

def status( self ):
        print "\nThe total number of critters is", Critter.total

to connect it to the class ( not sure for the exact terminology ) Of course now you have to call the method with an instance of the class because it is not static anymore :)

as for the second question:
The mandatory 'self' argument in the constructor is used in the whole class as a parameter to the methods. So 'self' refers to the self in the __init__( self ) constructor and allows you to use all variables that you have in the constructor like self.__mood or self.name. When you pass self as an argument to a method, all variables associated with self are available for use.

Basically you can play around with it and check different situations. Note that I may be mistaken somewhere so please correct me if I'm wrong :)

hope this helps :)

I have to prgrams and thus, two question to ask. In the following program how does the line status = staticmethod(status) do anything? My python programming book somehow connects it to the line Critter.total += 1 but I don't see how? Please explain.

# Classy Critter
# Demonstrates class attributes and static methods

class Critter(object):
    """A virtual pet"""
    total = 0
    
    
    def status():
        print "\nThe total number of critters is", Critter.total
        
    status = staticmethod(status)
        
    def __init__(self, name):
        print "A critter has been born!"
            
        self.name = name
            
        Critter.total += 1
            
            
# main

print "Accessing the class attribute Critter.total:",
print Critter.total

print "\nCreating critters."

crit1 = Critter("critter 1")
crit2 = Critter("critter 2")
crit3 = Critter("critter 3")

Critter.status()

print "\nAccessing the class attribute through an object:",
print crit1.total

raw_input("\n\nPress the enter key to exit.")

---------------------------------------------------------------------------------
I am going to answer the first question: How does staticmethod(status) equate back to Critter.total +=1?

Here is how it goes back to that, if you look at the last part of the function that is status you will see that it clearly references Critter.total. Now the only other place that Critter.total is in the code is when Critter.total += 1 is called.

I hope this clears it up a little for you

def status():
        print "\nThe total number of critters is", Critter.total
        
    status = staticmethod(status)

This allows class function status() to be called with the class name rather than the instance name ( an instance name wouldn't work because status() is a function, not a method like status(self) ).

Critter.total += 1 counts the number of times a class instance is created. It is need for the class function and connects to the instance too since total is global to the class methods.

I prefer to use methods in classes, then you can apply the decorator @classmethod to make make things less complex!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.