Python数据结构基础(三)——类(Class)

版权声明:本文版权归作者所有,未经允许不得转载! https://blog.csdn.net/m0_37827994/article/details/86492188

二、类

类是Python中面向对象编程的基本部分。

# Creating the class
class Pets(object):
  
    # Initialize the class
    def __init__(self, species, color, name):
        self.species = species
        self.color = color
        self.name = name

    # For printing  
    def __str__(self):
        return "{0} {1} named {2}.".format(self.color, self.species, self.name)

    # Example function
    def change_name(self, new_name):
        self.name = new_name
# Creating an instance of a class
my_dog = Pets(species="dog", color="orange", name="Guiness",)
print (my_dog)
print (my_dog.name)

输出结果:

orange dog named Guiness.
Guiness
# Using a class's function
my_dog.change_name(new_name="Charlie")
print (my_dog)
print (my_dog.name)

输出结果:

orange dog named Charlie.
Charlie

猜你喜欢

转载自blog.csdn.net/m0_37827994/article/details/86492188