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

2025-12-11 03:56:29

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、class Ball:

    def __init__(self):

        print("There are lots of balls.")

        self.name = "kick"

        

    def moving(self):

        print("%s the balls." % self.name)

        

football = Ball()

football.moving()

当然这个属性可以配合方法一起使用。

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

8、class Ball:

    def __init__(self):

        print("There are lots of balls.")

        self.name = "kick"

        

    def moving(self):

        print("%s the balls." % self.name)

        

football = Ball()

football.moving()

basketball = Ball()

basketball.moving()

但是如果我要让篮球拥有同一个方法,但是不同的属性要怎么办呢?

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

9、class 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里对类进行属性的添加

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢