网站首页 美食营养 游戏数码 手工爱好 生活家居 健康养生 运动户外 职场理财 情感交际 母婴教育 生活知识 知识问答

如何在PYTHON里对类进行属性的添加

时间:2024-10-13 06:12:16

1、打开JUPYTER NOTEBOOK,新建一个PY文档。

如何在PYTHON里对类进行属性的添加

2、class Ball:这里设置一个类,叫做球类,务必记得把类的第一个写为大写。

如何在PYTHON里对类进行属性的添加

3、class Ball: def __init__():__init__是初始化方法,为对象设置类可以具有什么属性。

如何在PYTHON里对类进行属性的添加

4、class Ball: def __init__(self):特别要注意的是,这里传入的第一个参数要为self,不要忘记添加。

如何在PYTHON里对类进行属性的添加

5、class Ball: def __init__(self): print("There are lots of balls.")然后像定义函数一样,添加属性。比如设置一个打印语句作为属性。

如何在PYTHON里对类进行属性的添加

6、class Ball: def __init__(self): print("There are lots of balls.")football = Ball()这里我们直接定义一个对象叫做football,就会直接返回这个类的属性。

如何在PYTHON里对类进行属性的添加

7、clas衡痕贤伎s Ball: def __init__(self): print("There are lots of ba造婷用痃lls.") self.name = "kick" def moving(self): print("%s the balls." % self.name) football = Ball()football.moving()当然这个属性可以配合方法一起使用。

如何在PYTHON里对类进行属性的添加

8、clas衡痕贤伎s Ball: def __init__(self): print("There are lots of ba造婷用痃lls.") self.name = "kick" def moving(self): print("%s the balls." % self.name) football = Ball()football.moving()basketball = Ball()basketball.moving()但是如果我要让篮球拥有同一个方法,但是不同的属性要怎么办呢?

如何在PYTHON里对类进行属性的添加

9、clas衡痕贤伎s Ball: def __init__(self, name): print("There are lots of balls.") self.move_name = name def moving(self): print("%s the balls." % self.move_name) football = Ball("kick")football.moving()basketball = Ball("play")basketball.moving()这个时候我们可以在初始化的时候,设置多一个参数在self的后面。

如何在PYTHON里对类进行属性的添加
© 2026 五度知识库
信息来自网络 所有数据仅供参考
有疑问请联系站长 site.kefu@gmail.com