1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのclass変数をCの静的変数のように使うテストプログラム '101回目のプロポーズ'

Last updated at Posted at 2023-12-02

class変数をCのstatic宣言された変数のように使ってみるテスト。
101回めのプロポーズ。ドラマの設定とはちょっと違いますが。

class yurieに101回呼び出したら'Yes'を返す関数ansを作ります。
メインからxを'Yes'が返ってくるまで呼び出します。
'Yes'が返ってきたら終了です。
クラス変数を使うとCの静的変数にもっと近くなりますが、ここでは、インスタンス変数を使ってます。

クラス変数はクラス共通の静的変数となり、インスタンス変数はインスタンス共通の静的変数となります。

propose.py
#!/usr/bin/env python3

import random

class yurie:
    def __init__(self):
        self.counter=0
        random.seed()
        return
    def ans(self):
        self.counter+=1
        if self.counter==101:
            return "Yes"
        return "mmm" if random.randrange(10)<7 else "No"

if __name__=="__main__":
    trial=0
    y=yurie()
    while 1:
        trial+=1
        print(f"{trial}回目")
        print("Me: Marry me please.")
        ans=y.ans()
        print(f"Yurie: {ans}.")
        if ans=="Yes":
            break
    print("We are just married.")

Cで書くとこのようになります。

propose.c
#include	<stdio.h>
#include	<stdlib.h>
#include	<string.h>
#include	<time.h>

void	yurie_init() {
	srand((unsigned)time(NULL));
	return;
}

char	*yurie_ans() {
	static int counter=1;
	return counter++==101?"Yes":(rand()%10<7?"mmm":"No");
}
int main() {
	int trial=0;
	char *ans;
	yurie_init();
	while (1) {
		trial++;
		printf("%d回目\n",trial);
		printf("Me: Marry me please.\n");
		ans=yurie_ans();
		printf("Yurie: %s.\n",ans);
		if (strcmp(ans,"Yes")==0)
			break;
		}
	printf("We are just married.\n");
}



1
0
12

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?