-1

私はPythonでクラスを学んでおり、ドキュメントを読んでいたときに、理解できないこの例を見つけました:

class MyClass:
    """A simple example class"""
    def __init__(self):
        self.data = []
        i = 12345
    def f(self):
        return 'hello world'

次に、を割り当てると:

x = MyClass()
x.counter = 1

while ループを実装すると、次のようになります。

while x.counter < 10:
       x.counter = x.counter * 2

x.counter の値は次のようになります。

16

たとえば、変数 y がある場合:

y = 1
while y < 1 :
   y = y *2

次に、y の値を探すと、それが見つかります

1

だから私はどのようにしてカウンターの値が 16 になったのか分かりません。

ありがとう

4

2 に答える 2

3

これは特にクラスとは何の関係もありませんが、ここで何が起こっているのか...

x == 1 # x is less than 10, so it is doubled
x == 2 # x is less than 10, so it is doubled
x == 4 # x is less than 10, so it is doubled
x == 8 # x is less than 10, so it is doubled
x == 16 # now x is greater than 10, so it is not doubled again
于 2012-11-20T17:07:08.587 に答える
1
y = 1
while y < 1 :
   y = y *2

同じ出力が必要な場合は、常に同じ入力を指定してください。

y < 1最初の実行でどちらが失敗するかを確認していることがわかります。y < 10あなたがあなたの場合に持っているように、それを作ってくださいx.counter

y = 1
while y < 10:
   y = y *2
于 2012-11-20T16:59:10.387 に答える