0
  1. 如何在 python 对象中声明默认值?

如果没有 python 对象,它看起来很好:

def obj(x={123:'a',456:'b'}):
    return x
fb = obj()
print fb

使用 python 对象,我收到以下错误:

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]
fb = foobar()
print fb.x

Traceback (most recent call last):
  File "testclass.py", line 9, in <module>
    print fb.x
AttributeError: 'NoneType' object has no attribute 'x'
  1. 如何让对象返回对象中变量的值?

使用 python 对象,我得到一个错误:

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]

fb2 = foobar({678:'c'})
print fb2.getStuff(678)

Traceback (most recent call last):
  File "testclass.py", line 8, in <module>
    fb2 = foobar({678:'c'})
TypeError: foobar() takes no arguments (1 given)
4

3 回答 3

5

你没有定义一个类,你定义了一个带有嵌套函数的函数。

def foobar():
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self,field):
        return x[field]

用于class定义一个类:

class foobar:
    def __init__(self,x={123:'a',456:'b'}):
        self.x = x
    def getStuff(self, field):
        return self.x[field]

请注意,您需要参考self.x.getStuff()

演示:

>>> class foobar:
...     def __init__(self,x={123:'a',456:'b'}):
...         self.x = x
...     def getStuff(self, field):
...         return self.x[field]
... 
>>> fb = foobar()
>>> print fb.x
{456: 'b', 123: 'a'}

请注意,对函数关键字参数 default 使用可变值通常不是一个好主意。函数参数定义一次,并且可能导致意外错误,因为现在您的所有类都共享同一个字典。

请参阅“Least Astonishment”和可变默认参数

于 2013-09-04T09:44:25.120 回答
1

要在 python 中定义一个类,你必须使用

    class classname(parentclass):
        def __init__():
            <insert code>

使用您的代码,您声明的是方法而不是类

于 2013-09-04T09:45:00.920 回答
1

利用

class foobar:

代替

def foobar():
于 2013-09-04T09:45:22.893 回答