程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python | single underline and double underline accessibility

編輯:Python

Environmental Science : Python 3.10.4

1. summary

Put the summary first

Underline Double underline Class properties and methods TrueFalse Subclasses call parent class properties and methods TrueFalse Module function TrueTrue

In the actual development process , Calling... Is strongly deprecated _ or __ Content at the beginning , image __str__ Except for .

2. class

2.1. attribute

class Hello:
def __init__(self, one, two):
self._one = one
self.__two = two
h = Hello(1, 2)
print(h._one)
print(h.__two)

Output

1
Traceback (most recent call last):
File "/Users/yimt/Code/PycharmProjects/hello-python/hello.py", line 9, in <module>
print(h.__two)
AttributeError: 'Hello' object has no attribute '__two'

2.2. Method

class Hello:
def _one(self):
print('one')
def __two(self):
print('two')
h = Hello()
h._one()
h.__two()

Output

Traceback (most recent call last):
File "/Users/yimt/Code/PycharmProjects/hello-python/learn.py", line 1, in <module>
import hello
File "/Users/yimt/Code/PycharmProjects/hello-python/hello.py", line 11, in <module>
h.__two()
AttributeError: 'Hello' object has no attribute '__two'
one

3. modular

The program runs normally

hello.py

def _one():
print('one')
def __two():
print('two')

main.py

import hello
hello._one()
hello.__two()

Output

one
two

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved