導航:首頁 > 編程語言 > python怎麼寫類

python怎麼寫類

發布時間:2024-07-13 01:31:13

python怎麼動態創建類

首先我們建一個目錄 my_moles,其中包括三個文件

* init.py: 模塊文件
* my_mole.py: 測試用的模塊
* my_another_mole:
另一個測試用的模塊

my_mole.py
from my_moles.my_another_mole import *
class MyObject(object):
def test(self):
print 'MyObject.test'
MyObject1().test()
MyObject2().test()
MyAnotherObject().test()
class MyObject1(object):
def test(self):
print 'MyObject1.test'
class MyObject2(object):
def test(self):
print 'MyObject2.test'

my_another_mole.py
class MyAnotherObject(object):
def test(self):
print 'MyAnotherObject.test'

test.py
def createInstance(mole_name, class_name, *args, **kwargs):
mole_meta = __import__(mole_name, globals(), locals(), [class_name])
class_meta = getattr(mole_meta, class_name)
obj = class_meta(*args, **kwargs)
return obj
obj = createInstance("my_moles.my_mole", "MyObject")
obj.test()
MyObject.test
MyObject1.test
MyObject2.test
MyAnotherObject.test

② python 類的定義

Python編程中類定義,代碼如下:

class<類名>:
<語句>

定義類的專有方法:

__init__構造函數,在生成對象時調用
__del__析構函數,釋放對象時使用
__repr__列印,轉換
__setitem__按照索引賦值
__getitem__按照索引獲取值
__len__獲得長度
__cmp__比較運算
__call__函數調用
__add__加運算
__sub__減運算
__mul__乘運算
__div__除運算
__mod__求余運算
__pow__稱方

代碼如下:

#類定義
classpeople:
#定義基本屬性
name=''
age=0
#定義私有屬性,私有屬性在類外部無法直接進行訪問
__weight=0
#定義構造方法
def__init__(self,n,a,w):
self.name=n
self.age=a
self.__weight=w
defspeak(self):
print("%sisspeaking:Iam%dyearsold"%(self.name,self.age))

p=people('tom',10,30)
p.speak()

③ python創建類的方法實例

創建一個學生類:

數據:(姓名,姓別,年齡 ,分數)

形為:列印信息

'''

class Studons:

def __init__(self,name,xibie,nianling,fenshu):

self.name=name

self.xibie=xibie

self.nianling=nianling

self.fenshu=fenshu

def dayin(self):

print("姓名:%s,性別:%s,年齡:%d,分數:%d"%(self.name,self.xibie,self.nianling,self.fenshu))

list_stud_xi=[]

while True:

qr=input("y繼續,n退出")

if qr=="y":

name=input("請輸入學生姓名:")

xingbie = input("請輸入學生性別:")

nianli=int(input("請輸入學生年齡:"))

fenshu=int(input("請輸入學生分數:"))

stu = Studons(name, xingbie, nianli, fenshu)#stu儲存的是類變數數據。

list_stud_xi.append(stu)#列表元素是類變數數據。

else:

break

for str in list_stud_xi:

str.dayin()

one=list_stud_xi[0]

one.dayin()

one.name="李剛"

one.fenshu=78

print(one.name,one.fenshu)

閱讀全文

與python怎麼寫類相關的資料

熱點內容
資料庫查詢系統源碼 瀏覽:617
php5314 瀏覽:357
完美國際安裝到哪個文件夾 瀏覽:667
什麼app可以掃一掃做題 瀏覽:538
程序員編碼論壇 瀏覽:923
淘點是什麼app 瀏覽:658
中國高等植物pdf 瀏覽:453
51單片機時間 瀏覽:182
後台如何獲取伺服器ip 瀏覽:267
單片機流水燈程序c語言 瀏覽:234
程序員第二職業掙錢 瀏覽:238
運行里怎麼輸入伺服器路徑 瀏覽:840
pythonstepwise 瀏覽:509
劉一男詞彙速記指南pdf 瀏覽:64
php認證級別 瀏覽:368
方舟編譯啥時候推送 瀏覽:1011
php手機驗證碼生成 瀏覽:675
哲學思維pdf 瀏覽:14
凌達壓縮機有限公司招聘 瀏覽:534
weblogic命令部署 瀏覽:36