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

二、类

类是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

你可能感兴趣的:(深度学习-python编程)