`
dacoolbaby
  • 浏览: 1254379 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

Python OO学习

阅读更多

 

#!/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

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics