Computer >> Máy Tính >  >> Lập trình >> Python

Python - Sử dụng biến bên ngoài và bên trong lớp và phương thức

Python là một ngôn ngữ lập trình hướng đối tượng. Hầu hết mọi thứ trong Python đều là một đối tượng, với các thuộc tính và phương thức của nó. Lớp giống như một phương thức khởi tạo đối tượng hoặc "bản thiết kế" để tạo các đối tượng.

Các biến được định nghĩa bên ngoài lớp có thể được truy cập bởi bất kỳ lớp nào hoặc bất kỳ phương thức nào trong lớp chỉ bằng cách viết tên biến.

Ví dụ

# defined outside the class'
# Variable defined outside the class.
outVar = 'outside_class'    
print("Outside_class1", outVar)
''' Class one '''
class Ctest:
   print("Outside_class2", outVar)
   def access_method(self):
      print("Outside_class3", outVar)
# Calling method by creating object
uac = Ctest()
uac.access_method()
''' Class two '''
class Another_ Ctest_class:
   print("Outside_class4", outVar)
   def another_access_method(self):
      print("Outside_class5", outVar)
# Calling method by creating object
uaac = Another_ Ctest_class()
uaac.another_access_method()
The variables that are defined inside the methods can be accessed within that method only by simply using the variable name.
# defined inside the method'
'''class one'''
class Ctest:
   print()
   def access_method(self):
      # Variable defined inside the method.
      inVar = 'inside_method'
      print("Inside_method3", inVar)
uac = Ctest()
uac.access_method()
'''class two'''
class AnotherCtest:
   print()
   def access_method(self):
      print()
uaac = AnotherCtest()
uaac.access_method()