首页 > 解决方案 > 如何在不需要自变量的情况下使对象可访问?

问题描述

例如在 discord.py 中:

import discord
discord.Status.dnd

^ 另一个例子:

class Test:
    def __init__(self, word):
        print(word)

这项工作需要 A = Test("blah") ,但是我如何使它像 Test("blah") 而不是给它变量?

标签: pythonoopobjectdiscord.py

解决方案


你可以这样做:

class Test:
    word = ''

print(Test.word) #Will return ''
Test.word = 'Blah'
print(Test.word) #Will return 'Blah'

instance = Test()

print(instance.word) #Will return 'Blah'
instance.word = 'Wow'
print(instance.word) #Will return 'Wow'

print(Test.word) #Will still return 'Blah'

推荐阅读