0
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?

More than 5 years have passed since last update.

python3x: local variable 'some_var' referenced before assignment inside of a class

Posted at

学校の授業でObjected-Oriented-Programmingについて勉強したので試しに簡易クラスを作ってみたのだが、どうも思うように動かない。

class Student:
	def __init__(self, name, brain_size=10, energy=10):
		self.name = name
		brain_size = 10
		self.energy = 10

	def study(self):
		brain_size += 1
		energy -= 1
		print("your brain has gotten bigger by 1")

	def flunk(self):
		brain_size -= 1
		energy -= 1
		print("you brain has gotten smaller by 1")

		if brain_size == 0:
			print("your college life is over")
		else:
			print("Ah! I did it again")

	def eat(self):
		energy += 1
		print("can't eat anymore")

		if energy == 0:
			print("your life is over")
>>> tim = Student('tim')
>>> tim.name
'tim'
>>> tim.energy
10
>>> tim.study()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ex.py", line 8, in study
    brain_size += 1
UnboundLocalError: local variable 'brain_size' referenced before assignment

study()を呼ぶこと自体に関しては何も問題はないと思われる。ただfunc studyenergyを正しく認識してくれない。クラスでもちゃんとparameterに入れたし昨日GSIに言われたとおりに__init__の中にも入れた。mmmmmh

そこで見つけたのがこの記事。aha!クラス内の関数はselfしか受け取ると命じられてないのにenergy変数が渡されてきて「へっ?」ってなってることをこのエラーは伝えたかったのか。。。。

と思って試したが、

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: study() missing 2 required positional arguments: 'brain_size' and 'energy'

当たり前だよな。しかもこのやり方を使うとstudy()を呼ぶたびに毎回その時のvalueが入っているparameterstudyに渡さないといけないというとんでもない不都合が生じてしまう。。

そこで気づいたのが上記リンクの以下のコメント:

It should be either self.NumRid += 1 if it is an instance variable, or Person.NumRid += 1 if it is a class variable.

これだ!と思い以下のようにコードを編集。

class Student:
	def __init__(self, name, brain_size=10, energy=10):
		self.name = name
		self.brain_size = 10
		self.energy = 10

	def study(self):
		self.brain_size += 1
		self.energy -= 1
		print("your brain has gotten bigger by 1")

	def flunk(self):
		self.brain_size -= 1
		self.energy -= 1
		print("you brain has gotten smaller by 1")

		if brain_size == 0:
			print("your college life is over")
		else:
			print("Ah! I did it again")

	def eat(self):
		self.energy += 1
		print("can't eat anymore")

		if energy == 0:
			print("your life is over")
>>> tim = Student('Tim')
>>> tim.study()
your brain has gotten bigger by 1

これで問題なく動く!

0
0
0

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
0
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?