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

熱點內容
幼兒編程教育培訓多少錢 瀏覽:401
經常生氣有什麼東西能解壓 瀏覽:900
代理伺服器地址和埠可以怎麼填 瀏覽:62
unity5手游編譯模型 瀏覽:265
安卓無人機app源碼 瀏覽:808
pl1編程語言 瀏覽:801
台達plc編程換算指令大全 瀏覽:174
手機上的編程游戲 瀏覽:108
伺服器密碼機有什麼用 瀏覽:477
dos磁碟命令 瀏覽:955
單片機cpu52的功能 瀏覽:691
opc伺服器怎麼開發 瀏覽:373
覓喜是個什麼app 瀏覽:402
加密cd機 瀏覽:946
社保用什麼app繳納 瀏覽:313
nodevlinux 瀏覽:582
騰訊tt伺服器怎麼登錄密碼 瀏覽:898
windows命令提示符 瀏覽:352
win7管理員許可權命令 瀏覽:729
地圖app哪個適合老年人用 瀏覽:74