Dùng global để khởi tạo hàm/lớp

Cho em hỏi cách để dùng lệnh global khai báo một hàm hoặc lớp ạ

Đi học bao nhiêu năm giờ mới nghe xài global để khai báo function/class @@

Cứ vứt ngoài main thì là global thôi.

def fun(n):  # global
	return (n*n+1)//2

def sad(n):  # global
	return "Valungtung van chua co gau!\n" * n

def feeling(bored, n):  # global
	def define_res(n):
		if bored:
			return fun(n)  # call global def
		else:
			return sad(n*2)  # global def too
	
	def fake_n(n):
		return (n+n)//3
	
	return define_res(fake_n(n))

if __name__ == '__main__':
	print(feeling(True, 8))
	print(feeling(False, 8))

E cũng biết là thế, nhưng e đọc dòng này xong nhưng vẫn chưa biết “how to”


Link: https://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python

1 Like

1 link khác

You can’t create anything that’s truly global in Python - that is, something that’s magically available to any module no matter what.

Đọc 3 chữ đầu là thấy hết hi vọng :smile:

Mới thấy link khác, anh đọc thấy ảo diệu quá:

P/s: Anh code dùng global var bao nhiêu năm, giờ thấy code xấu hoắc :expressionless:

83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?