導航:首頁 > 編程語言 > 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怎麼寫類相關的資料

熱點內容
程序員面試評價 瀏覽:128
手錶加密門禁卡 瀏覽:238
psf已加密 瀏覽:553
返利app怎麼用教程 瀏覽:888
一個程序員寫的詩火了 瀏覽:613
red攝影機壓縮比 瀏覽:410
app賬號怎麼弄 瀏覽:823
hc0551單片機 瀏覽:755
噴淋管道支架演算法 瀏覽:592
壓縮機壞了電腦無法啟動 瀏覽:241
不小心加密了怎麼去掉 瀏覽:955
linux命令行連接db2 瀏覽:898
洪恩app怎麼設置護眼模式 瀏覽:971
小猿口算app怎麼選課時 瀏覽:421
手機號脫敏加密解密 瀏覽:169
台電加密u盤多少錢 瀏覽:547
控制面板文件夾怎麼隱藏 瀏覽:846
opticspdf 瀏覽:593
抖店app怎麼快速退保證金 瀏覽:972
阿里雲伺服器的密碼在哪改 瀏覽:908