python class access

python class access restrictions
have been in the self-python, because then no difficulty :( guide, so confused me a few hours)
beginner class, comes in contact with the method --init, but every time you run the program, the total there will be mistakes, full screen rosy. Read someone else's blog, know, I __init__ method labeled _init _. (Only an underscore).
Later, contact with the python class access restrictions, they would understand why it is double underlined.

foo: double underline, generally system-defined name
_foo: single underlined that begin with the type of protection (protected) types of members, allowing only the class itself and its subclasses access, can not be imported with "Import Module from"
__foo: begin with a double underscore represents private (private) member type, the class definition of only allow access to the process itself, and can not be accessed by the instance of the class, but can be "instance name of the class. class name __xxx" access

class Swan:
	__neck_swan = "long neck"
	#定义私有属性
	def __init__(self):
		print("__init__()", Swan.__neck_swan)
		#在实例方法中访问私有属性
		
swan = Swan()
print("Add name:", swan._Swan__neck_swan)
#通过 “实例名。类名__xxx”访问私有属性
print(swan.__neck_swan)
#私有属性不能通过实例名访问,出错
Released seven original articles · won praise 1 · views 159

Guess you like

Origin blog.csdn.net/m0_46236946/article/details/104118538