在Python中打印类的变量
我是Python的新手,现在正在玩弄这些类 看看这个简单的代码在Python中打印类的变量,python,Python,我是Python的新手,现在正在玩弄这些类 看看这个简单的代码 class Testing: BB_Key_Length = {256 : 240} #method __init__() is a special method, which is called class constructor or initialization method that #Python calls when you create a new instance of this class.
class Testing:
BB_Key_Length = {256 : 240}
#method __init__() is a special method, which is called class constructor or initialization method that
#Python calls when you create a new instance of this class.
def __init__(self, key_length):
self._key_length = key_length
self._n = int(key_length / 8)
if key_length in self.BB_Key_Length:
self._b = self.BB_Key_Length[key_length]
print(self._b)
Object1 = Testing(200)
print(Testing.BB_Key_Length)
第13行写着,print(self.\b)
,它也在\uuuu init\uuuu
函数中,但为什么self.\u b的值在我创建对象时没有打印
Object1 = Testing(200)
我只想打印我无法打印的self.\u b
的值
为什么在创建对象时self.\u b的值没有打印Object1=Testing(200)
因为print语句在if语句中,这是错误的,因为200不是dict
self.BB\u key\u Length
中的键,因为self.BB\u key\u Length中的行if key\u Length
。如果不满足该条件,则不会出现行print(self.\u b)
。实际上,key\u length
将等于200,200不在字典{256:240}
中,但200在240和256之间。为什么不打印呢?字典不是这样工作的如果self.BB_Key_Length中有200,只需检查self.BB_Key_Length中是否有等于200的密钥。但是在self.BB\u key\u Length中只有一个键,即256。但是200在240和256之间。为什么不打印then@Xufyan那不是一个范围。这是一个dict。如果您想要一个范围,请使用range
@Xufyan,200也不在范围内(240256)。@Xufyan,dict
是一个映射、函数,一个容器,它为每个键a
返回一个相关值B
。在您的例子中,您已经定义了一个字典(dict
),其中包含一个值为240
256
的单键