日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python中init和属性_python类的属性不在\uyu init中__

發(fā)布時間:2023/12/20 python 36 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中init和属性_python类的属性不在\uyu init中__ 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

它是類屬性、實例屬性和動態(tài)屬性。當您這樣做時:class Car():

def __init__(self):

pass

c = Car()

c.speed = 3

c.time = 5

speed和time是動態(tài)屬性(不確定這是否是正式術(shù)語)。如果類的用法是在調(diào)用Car的任何其他方法之前設(shè)置這些屬性,那么這些方法可以使用self.speed。否則,將出現(xiàn)一個錯誤:

^{pr2}$

發(fā)生這種情況是因為對于c,速度和時間是Car實例的屬性。它們的存在或價值不會在其他Car實例中傳播。因此,當我創(chuàng)建d并嘗試查找d.speed時,該屬性不存在。正如你在自己的評論中所說的,“當它們第一次被分配到時,它們就會出現(xiàn)。”I accidentally found that I don't have to init attributes in init. I learn from every tutor I have to put assignment in init like below.

你的導師錯得很厲害,或者你誤解了他們的意思。在您給出的示例中,每輛車的首字母speed和{}。通常,__init__將如下所示:class Car():

def __init__(self, speed, time): # notice that speed and time are

# passed as arguments to init

self.speed = speed

self.time = time

然后您可以用Car初始化Car。或者在init中輸入默認值(如果是可選的)。在class Dog:

kind = 'canine' # class variable shared by all instances

def __init__(self, name):

self.name = name # instance variable unique to each instance

>>> d = Dog('Fido')

>>> e = Dog('Buddy')

>>> d.kind # shared by all dogs

'canine'

>>> e.kind # shared by all dogs

'canine'

>>> d.name # unique to d

'Fido'

>>> e.name # unique to e

'Buddy'

>>> d.age = 3 # dynamic attribute/variable, unique to d

>>> d.age

3

>>> e.age # e doesn't have it at all

Traceback (most recent call last):

File "", line 1, in

AttributeError: 'Dog' object has no attribute 'age'

總結(jié)

以上是生活随笔為你收集整理的python中init和属性_python类的属性不在\uyu init中__的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。