簡體   English   中英

如何從 class 方法為 class 變量分配新值?

[英]How to assign a new value for class variable from class methods?

x = int(input("enter x:"))
class hello:
    var = x

h = hello()

print(hello.var)

測試運行:

enter x:15
15

如何通過 class 的方法訪問 static 變量? 我被困在這個

如果你想讓hello.var有一個值,那么你可以給它賦值:

class hello:
    var = None

h = hello()
x = int(input("enter x:"))
h.var = x
print(hello.var)

您可以定義一個 class 方法來設置 class 變量

x = int(input("enter x:"))

class hello:
    var = x

    @classmethod
    def set_var(cls, value):
        cls.var = value

h = hello()
print(hello.var, h.var)
h.set_var('I am new var')
print(hello.var, h.var)

暫無
暫無

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

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