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"
>>> User.User.staticHi() Static Hi >>> john.staticHi() Static Hi
Static method can be called both by Class and instance.
Some topic about ‘slef’:
<<Learn Python the Hard Way>> Notes <->
// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.