在面向对象的python中访问变量和函数 - python

alv*_*vas 0 python oop variables init

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

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

def obj(x={123:'a',456:'b'}):
    return x
fb = obj()
print fb
Run Code Online (Sandbox Code Playgroud)

使用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'
Run Code Online (Sandbox Code Playgroud)
  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)
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

您没有定义类,您使用嵌套函数定义了一个函数.

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

使用class来定义一个类来代替:

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

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

演示:

>>> 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'}
Run Code Online (Sandbox Code Playgroud)

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

请参阅"最小惊讶"和可变默认参数.