python封裝的方法 Python類和封裝方法

2021-10-16 21:29:50 字數 1505 閱讀 8488

我是oop新手,這是我建立python類的第一次嘗試。我試圖使我的3個變數私有化,以便只有方法更新資訊(強制封裝)。似乎如果我從類中刪除setters和getters方法,它對我的**沒有影響(一定是初始化器方法在做這項工作嗎?)。我能做些什麼來改善這一點?謝謝。在

編輯-我已經更新了我的**並刪除了初始化。我的吸氣筒現在不工作了。在#instantiate a new pet instance.

mypet = pet()

#get input from user.

mypet.setname = input("enter the pet's name: ")

mypet.settypes = input("enter the pet's type (dog, cat, bird, etc.): ")

mypet.setage = input("enter the pet's age (in years): ")

while mypet.setage.isalpha():

print()

print("age cannot contain numbers. try again.")

mypet.setage = input("enter the pet's age (in years): ")

#call the showpetinfo module using new instanced object.

mypet.showpetinfo()

class pet:

#fields of the pet class.

__petname = ""

__pettype = ""

__petage = ""

#setter methods.

def setname(self,name):

self.__petname = name

def settypes(self,types):

self.__pettype = types

def setage(self,age):

self.__petage = age

#getter methods.

@property

def getname(self):

return self.__petname

@property

def gettype(self):

return self.__pettype

@property

def getage(self):

return self.__petage

def showpetinfo(self):

print("\n \n \n \n")

print("here is your pet's information. your pet's name is {}, it is a {} and it is {} years old.".format(self.getname,self.gettype,self.getage))

main()

用 PyInstaller 打包封裝python

pip install pyinstallertest.py 以及 test.png test2.png 用於介面顯示到圖示檔案。輸出乙個test 可以執行程式檔案,可直接執行。如 test.實際上,這個檔案可執行程式檔案是乙個包,執行過程中會將這個包解壓縮到 tmp mei 路徑下,執行結束會自動...

Python爬蟲,get方法的封裝

這裡比較規範的使用了工程化的思想,考慮了日誌的編寫 爬蟲傳送get請求時,則考慮了ua等http request head部分的設定 並且支援 伺服器的資訊處理 返回的狀態碼不是200時的處理 並且考慮了超時問題,及網頁的編碼問題 import sys import logging import u...

python 日誌log封裝方法

coding utf 8 import logging import time import os log path os.path.join os.path.dirname os.path.dirname os.path.realpath file logs a os.path.exists lo...