例子,python oop实现代码。
 
复制代码 代码示例:
#!/usr/bin/python  
# Filename: method.py  
class Person:  
    def sayHi(self):  
        print 'Hello, how are you?'  
  
p = Person()  
p.sayHi()  
 
Python中的self:
假如你有一个类称为MyClass和这个类的一个实例MyObject。
当你调用这个对象的方法MyObject.method(arg1, arg2)的时候,这会由Python自动转为MyClass.method(MyObject, arg1, arg2)——这就是self的原理了。
 
例子:
 
复制代码 代码示例:
#!/usr/bin/python  
# Filename: objvar.py  
  
class Person:  
    '''Represents a person.'''  
    population = 0  
  
    def __init__(self, name):  
        '''Initializes the person's data.'''  
        self.name = name  
        print '(Initializing %s)' % self.name  
  
        # When this person is created, he/she  
        # adds to the population  
        Person.population += 1  
  
    def __del__(self):  
        '''I am dying.'''  
        print '%s says bye.' % self.name  
  
        Person.population -= 1  
  
        if Person.population == 0:  
            print 'I am the last one.'  
        else:  
            print 'There are still %d people left.' % Person.population  
  
    def sayHi(self):  
        '''Greeting by the person.  
  
        Really, that's all it does.'''  
        print 'Hi, my name is %s.' % self.name  
  
    def howMany(self):  
        '''Prints the current population.'''  
        if Person.population == 1:  
            print 'I am the only person here.'  
        else:  
            print 'We have %d persons here.' % Person.population  
 
在这个方法中,让population增加1,这是因为增加了一个人。
同样可以发现,self.name的值根据ÿ个对象指定,这表明了它作为对象的变量的本质。
记住,只能使用self变量来参考同一个对象的变量和方法。这被称为 属性参考 。
用Java的语言来说,population是一个静态变量,通过self赋值的,才是成员变量。
 
Python中的toString()方法:
 
复制代码 代码示例:
class Person:  
    def __init__(self,name):  
        self.name = name  
          
    def __str__(self):  
        return 'name:'+self.name 
使用方式:
 
复制代码 代码示例:
p = Person('sam')
print p