Home  >  Q&A  >  body text

Python 实例创建传入参数问题

class FooClass(object):
    version = 0.1
    def __init__(self, nm='John Doe'):
        self.name = nm
        print 'Created a class instance for', nm

    def showname(self):
        print'Your name is', self.name
        print 'My name is', self.__class__.__name__

    def shower(self):
        print self.version

    def addMe2Me(self, x):
        return x+x

在学习Python,创建FooClass这个类的实例有几个问题:
1. 为什么参数是一个object
2. 如果通过如下代码创建给一个实例:

ddd = FooClass('dhl')

那么使用showname() 这个方法会显示:

ddd.showname()
Your name is dhl
My name is FooClass

而不传入参数的情况下,使用showname()这个方法会显示:

dhl = FooClass()
dhl.showname()
Your name is John Doe
My name is FooClass

object 这个创建时候的参数是通过什么机制,传递给实例的name属性的?
先谢谢了!

迷茫迷茫2720 days ago554

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-17 13:52:27

    The class definition brackets are not parameters, but the parent class

    The

    constructor is __init__, exposing a parameter nm, and it has a default value John Doe

    So FooClass('dhl') actually called

    new FooClass.__init__('dhl')
    

    As for the first parameter self defined in each function in the class, it is used to expose this指针 to the inside of the function body and is not exposed to the caller

    reply
    0
  • Cancelreply