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

Debug小技巧 – 为对象加入一个Object_ID Field

Categories: Development Notes; Tagged with: ; @ February 19th, 2009 23:07

使用Random来作为Field内容, 并重写toString, 便于在debug时分辨出名称相同的对象, 如:

某类: Employee: [ AS实现]:

	/**
	 * Constractor
	 */
	public function Employee(name_:String = null) {
		_name = name_;
		objectID = Math.random();
	}

//--------------------------toString-----------------

	public function toString():String {
		return name + " - " + objectID;
	}

未加id及覆盖toString前的输出信息:

[DEBUG] Controler Current Selceted Employee: [object Employee]

[DEBUG] Controler Current Selceted Employee: [object Employee]

[DEBUG] Controler Current Selceted Employee: [object Employee]

[DEBUG] Controler Current Selceted Employee: [object Employee]

加上之后:

[DEBUG] Controler Current Selceted Employee: Tom – 0.9672538451850414

[DEBUG] Controler Current Selceted Employee: Tom – 0.5573517205193639

[DEBUG] Controler Current Selceted Employee: Tom – 0.9672538451850414

[DEBUG] Controler Current Selceted Employee: Tom – 0.5573517205193639



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