python中init和属性_python类的属性不在\uyu init中__
它是類屬性、實例屬性和動態(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)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【弱监督显著目标检测论文】Weakly-
- 下一篇: php抓取快照,PHP抓屏函数实现屏幕快