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

它是类属性、实例属性和动态属性。当您这样做时:class Car():

def __init__(self):

pass

c = Car()

c.speed = 3

c.time = 5

speed和time是动态属性(不确定这是否是正式术语)。如果类的用法是在调用Car的任何其他方法之前设置这些属性,那么这些方法可以使用self.speed。否则,将出现一个错误:

^{pr2}$

发生这种情况是因为对于c,速度和时间是Car实例的属性。它们的存在或价值不会在其他Car实例中传播。因此,当我创建d并尝试查找d.speed时,该属性不存在。正如你在自己的评论中所说的,“当它们第一次被分配到时,它们就会出现。”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'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值