簡體   English   中英

在面向對象的python中訪問變量和函數-python

[英]Accessing variable and functions in object oriented python - python

  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)

您沒有定義類,而是定義了帶有嵌套函數的函數。

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.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'}

請注意,對於函數關鍵字參數default使用可變值通常不是一個好主意。 函數參數定義一次 ,並且可能導致意外錯誤,因為現在所有類都共享同一字典。

請參見“最少驚訝”和可變默認參數

在python中定義一個類,你必須使用

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

使用您的代碼,您聲明的是方法而不是類

采用

class foobar:

代替

def foobar():

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM