有关于自我的问题,但我找不到任何好的和易于理解的解释为什么我不能这样做以及我应该如何正确地做到这一点。如何处理它对我和许多其他开始使用python的人来说非常违反直觉。例如:
class cls:
def __init__(self):
self.a = True
if self.a:
print("self.a is True")
else:
print("self.a if False")
我不知道如何在类中访问或检查init之外的“a”。如果我会做这样的事情:
class cls:
def __init__(self):
self.a = True
if a:
print("a is True")
else:
print("a if False")
然后我得到NameError。在某些时候,我总是遇到这个问题,我无法理解如何正确处理这个问题。我应该在课外做功能吗?无论你尝试什么都应该有意义,在这种情况下是行不通的。另一个例子:
class cls:
def __init__(self):
self.a = True
if cls.a:
print("self.a is True")
else:
print("self.a if False")
给出IndentationError:意外缩进。
答案 0 :(得分:0)
您似乎只需将代码包装在以下函数中:
class myClass():
def __init__(self):
self.a = True
def check_a(self):
if self.a:
print('a is True')
else:
print('a is not True')
并使用它:
inst = myClass()
inst.check_a()
会做你想要的,打印:'a is True'
希望可以稍微澄清一下。