三分钟学习一个python小知识2-----------我的对python的类(Class)和对象(Object)的理解

在这里插入图片描述



一、(Class)和对象(Object)是什么?

Python是一种面向对象的编程语言,其基本的面向对象编程机制就是类(Class)和对象(Object)。
类是一种定义对象属性和方法的蓝图或模板。 它们是一种代码结构,可以包含属性存储和函数操作,从而使其更有结构和可读性。对象则是这些类的一个实例化结果,拥有类定义的属性和方法,并可以使用它们在程序中进行操作。

二、Python类和对象的实现

1.定义类

在 Python 中,一个class类的定义以关键字 class 开始,后面跟类的名称。类名后面的括号中可以包含父类的名称,如果一个类没有父类,则写为 object。类定义以冒号(:)结尾,下面是一个简单的定义类的例子:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"Hi, my name is {
      
      self.name}, and I am {
      
      self.age} years old.")

2.创建对象

在 Python 中,对象是类的实例化。实例化是一个过程,通过它我们可以创建 Python 的对象。可以使用类的名称来创建一个对象。下面是一个创建一个对象的例子:

student1 = Student('Tom', 20)
student2 = Student('Jack', 21)

3.调用类的属性和方法

类的属性可以通过对象名.属性名的形式来调用,类的方法可以通过对象名.方法名的形式来调用。下面是一个访问类属性和方法的例子:

student1.name  # 访问对象的属性
student1.introduce()  # 调用对象的方法

三、利用python实现了一个动物的类(Animal)和其两个子类(Cat和Dog)

# 定义动物类
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print(f"I am {
      
      self.name}, and I am {
      
      self.age} years old.")

    def eat(self):
        print("I am eating.")

# 定义猫类
class Cat(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)
        self.color = color

    def introduce(self):
        print(f"I am {
      
      self.name}, and I am {
      
      self.color} in color. I am {
      
      self.age} years old.")

    def sleep(self):
        print("I am sleeping.")

# 定义狗类
class Dog(Animal):
    def __init__(self, name, age, breed):
        super().__init__(name, age)
        self.breed = breed

    def introduce(self):
        print(f"I am {
      
      self.name}, and I am {
      
      self.breed} breed. I am {
      
      self.age} years old.")

    def bark(self):
        print("I am barking.")

# 创建猫对象和狗对象,并调用它们的方法
cat1 = Cat("Kitty", 2, "Gray")
cat1.introduce()  # 输出:I am Kitty, and I am Gray in color. I am 2 years old.
cat1.eat()  # 输出:I am eating.
cat1.sleep()  # 输出:I am sleeping.

dog1 = Dog("Puppy", 3, "Golden Retriever")
dog1.introduce()  # 输出:I am Puppy, and I am Golden Retriever breed. I am 3 years old.
dog1.eat()  # 输出:I am eating.
dog1.bark()  # 输出:I am barking.

总结

这个例子中,Animal类是父类,Cat和Dog是它的子类。Cat和Dog都继承了Animal类的属性和方法,并且它们各自实现了自己的一些额外的方法。通过创建Cat和Dog对象来实例化这两个类,并调用它们的方法来展示类和对象的用法。

猜你喜欢

转载自blog.csdn.net/qlkaicx/article/details/131331356
今日推荐