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

熱點內容
代碼加密常用方法 瀏覽:950
安卓手機如何解除已禁用 瀏覽:396
演算法的隨機性 瀏覽:485
高中解壓體育游戲 瀏覽:532
androidstudior丟失 瀏覽:345
命令行筆記 瀏覽:737
360目標文件夾訪問拒絕 瀏覽:518
3b編程加工指令 瀏覽:789
c8051f系列單片機選型手冊 瀏覽:772
南昌php程序員 瀏覽:511
bcs命令 瀏覽:446
如何在伺服器指向域名 瀏覽:417
車床編程可以做刀嗎 瀏覽:519
ln命令源碼 瀏覽:791
用粘液做解壓手套 瀏覽:331
icloud收信伺服器地址 瀏覽:500
編程思考者 瀏覽:453
壓縮機型號用什麼氟利昂 瀏覽:553
農機空氣壓縮機 瀏覽:666
程序員下載歌曲 瀏覽:897