Python 实例创建传入参数问题
迷茫
迷茫 2017-04-17 13:50:27
0
1
552
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属性的?
先谢谢了!

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
刘奇

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!