如果我们删除函数中的全局变量并在函数中重新创建相同的变量,以便我们无法在函数外部访问它,但是在删除方式后仍然可以访问它?
代码:
f=100
print(f)
def change():
global f
print(f)
f=200
print(f)
del f #deleted
#print(f) we get error for this line
f=500# again created as local variable
g=5000# this is also local means can't access outside the function
print(f)
change()
print(f)#We delete f but how it exist.although it is local var of change function
print(g)#Here we get error that g is not defined
答案 0 :(得分:1)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:background="@color/bluCotral"
android:orientation="horizontal"
>
<Button
android:id="@+id/btn_back"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginStart="10dp"
android:background="@drawable/bottone_torna_indietro"
android:layout_gravity="center"
/>
<Button
android:id="@+id/btn_esci"
android:layout_width="55dp"
android:layout_height="40dp"
android:layout_marginStart="220dp"
android:backgroundTint="@color/bianco"
android:text="esci"
android:layout_gravity="center"
/>
</LinearLayout>
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
>
</FrameLayout>
</LinearLayout>
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_inizia_missione, container, false);
final View rootView = inflater.inflate(R.layout.activity_main, container, true);
Button back = rootView.findViewById(R.id.btn_back);
back.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
Toast toast = Toast.makeText(getContext() , "prova", Toast.LENGTH_SHORT);
toast.show();
}
});
return view;
}
被声明为全局;当您重新创建它时,它将在全局范围内重新创建。
另一方面,f
是本地的,无法在其范围之外访问。
g