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

熱點內容
什麼是戰略pdf 瀏覽:517
20萬人用什麼伺服器 瀏覽:926
反編譯怎麼解決字串長度 瀏覽:279
農行app怎麼凍結賬號 瀏覽:759
mt反編譯的軟體打不開 瀏覽:518
安卓日上免稅APP如何安裝 瀏覽:583
怎麼買星空加密狗 瀏覽:19
北京程序員薪酬 瀏覽:133
華為榮耀暢玩8c升級方舟編譯器 瀏覽:412
手機怎麼把照片填入文件夾 瀏覽:305
php圖片輪換 瀏覽:929
科二學車app軟體哪個好 瀏覽:645
用aj踩東西的解壓視頻 瀏覽:382
將python編譯成手機app 瀏覽:475
程序員社招國企好進么 瀏覽:696
php路徑寫法 瀏覽:432
為什麼有些網頁安卓打不開 瀏覽:220
如何滲透獲取伺服器資料庫 瀏覽:778
ios是怎麼解析app的 瀏覽:256
按揭車怎麼貸款app 瀏覽:477