簡體   English   中英

在Python中制作跨模塊變量-在類和函數中

[英]Making a variable cross module in Python - Within a class and function

我正在嘗試在其他python模塊中使用變量,如下所示:

a.py

class Names:
    def userNames(self):
        self.name = 'Richard'

z.py

import a
d = a.Names.name
print d

但是,這無法識別變量name並且收到以下錯誤:

AttributeError: type object 'Names' has no attribute 'name'

謝謝

“我再次檢查過,這是因為我從中導入的是一個Tornado框架,並且該變量在一個類內。”

因此,您的問題不是問題中顯示的問題。

如果您實際上想要訪問類的變量(並且可能不想訪問),請執行以下操作:

from othermodule import ClassName

print ClassName.var_i_want

您可能想要訪問實例中保存的變量:

from othermodule import ClassName, some_func

classnameinstance = some_func(blah)
print classnameinstance.var_i_want

更新現在,您已經完全更改了問題,這是新問題的答案:

在此代碼中:

class Names:
    def userNames(self):
        name = 'Richard'

name是在方法userNames激活之外不可訪問的變量。 這稱為局部變量。 您可以通過將代碼更改為以下內容來創建實例變量:

def userNames(self):
        self.name = 'Richard'

然后,如果在名為classnameinstance的變量中有一個實例,則可以執行以下操作:

print classnameinstance.name

僅當在實例上已經創建了變量(例如通過調用userNames ,這才起作用。

如果還有其他接收類實例的方法,則不需要導入類本身。

變量可以綁定到許多不同的作用域,這似乎使您感到困惑。 這里有一些:

# a.py
a = 1 # (1) is module scope

class A:
    a = 2 # (2) is class scope

    def __init__(self, a=3): # (3) is function scope
        self.a = a           # (4) self.a is object scope

    def same_as_class(self):
        return self.a == A.a # compare object- and class-scope variables

    def same_as_module(self):
        return self.a == a   # compare object- and module-scope variables

現在,看看這些不同的變量(我只是稱呼它們為a ,請不要真正使用它)是如何命名的,以及它們如何具有不同的值:

>>> import a
>>> a.a
1 # module scope (1)
>>> a.A.a
2 # class scope (2)
>>> obj1 = a.A() # note the argument defaults to 3 (3)
>>> obj1.a       # and this value is bound to the object-scope variable (4)
3
>>> obj.same_as_class()
False             # compare the object and class values (3 != 2)

>>> obj2 = a.A(2) # now create a new object, giving an explicit value for (3)
>>> obj2.same_as_class()
True

請注意,我們還可以更改以下任何值:

>>> obj1.same_as_module()
False
>>> obj1.a = 1
>>> obj1.same_as_module()
True

作為參考,您上面的z.py可能看起來像:

import a
n = a.Names()
d.userNames()
d = n.name
print d

因為a.Name是一個class ,但是您正在嘗試引用一個對象范圍變量。 對象是類的實例:我已經將實例n稱為。 現在我有了一個對象,我可以得到object-scope變量。 這相當於Goranek的答案。

就我之前的示例而言,您試圖訪問obj1.a而沒有obj1或類似對象。 我真的不確定如何弄清楚這一點,而不將其轉變為有關OO和Python類型系統的介紹性文章。

文件:a.py

class Names:
    def userNames(self):
        self.name = 'Richard'

文件:z.py

import a
c = a.Names()
c.userNames()
what_you_want_is = c.name

順便說一句,這段代碼沒有任何意義..但這顯然是您想要的

更好的a.py

class Names:
    def userNames(self, name):
        self.name = name

更好的z.py

import a
c = a.Names()
c.userNames("Stephen or something")
what_you_want_is = c.name 
# what_you_want_is is "Stephen or something"

暫無
暫無

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

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