面向对象编程疑惑:Python OOP实例与理解
Python作为一种面向对象的编程语言,它的OOP(Object-Oriented Programming)特性主要体现在以下几个方面:
类(Class):是OOP的核心概念。在Python中,我们定义一个类使用
class
关键字。class Animal:
def __init__(self, name):
self.name = name
# 方法声明
对象(Object):类创建后,就产生了一系列的对象。每个对象都具有类中定义的属性和方法。
animal1 = Animal("Lion"))
print(animal1.name) # 输出 "Lion"
animal2 = Animal("Tiger"))
print(animal2.name) # 输出 "Tiger"
继承(Inheritance):类与类之间的关系。子类可以继承父类的属性和方法。
class Mammal:
def __init__(self, species):
self.species = species
# 共享方法声明
def make_sound(self):
return f"{self.species} sounds."
class Dog(Mammal):
def __init__(self, name):
super().__init__("Canine")
self.name = name
dog1 = Dog("Rex")
print(dog1.make_sound()) # 输出 "Canine sounds. Rex"
通过以上例子,你应该对Python的面向对象编程有了基本的理解。如果你还有疑问或者想要深入学习,可以继续提问。
还没有评论,来说两句吧...