設置私有屬性以後,如何修改私有屬性python
class Room: def __init__(self,name,length,width): self.__name = name self.__length = length self.__width = width def get_name(self): return self.__name def set_name(self,newName): #約束 if type(newName) is str and newName.isdigit() == False: self.__name = newName #這樣寫的好處是。不能讓別人隨意修改。 #起到一個保護做用。 else: print("姓名不合法") def area(self): return self.__length * self.__width room = Room("小明",2,4) print(room.area()) room.set_name("2") print(room.get_name())
#問題:父類的私有屬性,可否被子類調用。
#結果:不能被調用。
class Foo: __key = "保險櫃的鑰匙" #_Foo_key class Foo2(Foo): print(Foo.__key) #_Foo2_key
父類的私有屬性,能不能被子類調用的。