My first Python Class

Categories: Python; Tagged with: ; @ May 14th, 2014 23:24

User class, has one attribute ‘name’: 

#User.py
class User(object):
        def __init__(self, name):
                self.name=name

        def sayHi(self):
                print self.name, " say hi to you"


        def hello(self, *friends):
                f1, f2 = friends
                print "hello my friends: ", f1", and ", f2

Initialize User instance and call the methods:

>>> import User
>>> john = User.User("John")
>>> john.sayHi()
John  say hi to you
>>> john.hello("Luna", "Peter")
hello my friends:  Luna  and  Peter

I got confused, because I come from Java, why every method need a ‘self’? we use the instance invoke the method,  why we need to supply the instance itself?

Maybe they are static?  let’s try to invoke the method in ‘Static’ way:

>>> User.User.sayHi()
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unbound method sayHi() must be called with User instance as first argument (got nothing instead)

Ok, how about this:

>>> User.User.sayHi(john)
John  say hi to you

It seems these instance method can be invoked both by Class and instance… that’s why  every method requires a ‘self’?

Ok, let’s add a static method:

        @staticmethod
        def staticHi():
                print "Static Hi"

Invoke it:

>>> User.User.staticHi()
Static Hi
>>> john.staticHi()
Static Hi

Static method can be called both by Class  and instance.

 

Some topic about ‘slef’:

http://stackoverflow.com/questions/2709821/python-self-explained

http://neopythonic.blogspot.sg/2008/10/why-explicit-self-has-to-stay.html

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.