简介
Python 使用类来实现面向对象编程。类定义使用 class 关键字,方法使用缩进来表示
- 构造方法:
在Python类的构造函数为__init__(self)
,该方法的第一个参数必需是self
,它是对类实例的引用,如在对象(类实例)初始化时需要传递其它参数可写在self
后面; - Python类中变量、方法的访问修饰符:
在Python中是通过名称修饰符_
来实现C++中Public、Protected、Private访问修饰符的:- 公开的方法或变量(public):当变量或方法以字母开头时则为公开的方法或变量;
- 保护的方法或变量(protected):当变量或方法以
_
开头时则保护的方法或变量;注意:Python中的保护类型仅是命名约定,并没有强制限制 - 私有的方法或变量(private):当变量或方法以
__
开头时则私有的方法或变量;在派生类中不可访问基类的私有方法或变量
示例代码
class Class_Demo:
def __init__(self):
self.public_variable = "This is a public variable"; #公共变量
self._protected_variable = "This a protected variable"; # 保护类型变量
self.__private_variable = "This is a private variable"; # 私有变量
class_demo = Class_Demo();
print(class_demo.public_variable); #公有变量可正常输出
print(class_demo._protected_variable); #仍可输出
print(class_demo.__private_variable); #报错
输出如下
D:\Code4\Python_Demo> python py_class_demo.py
This is a public variable
This a protected variable
Traceback (most recent call last):
File "D:\Code4\Python_Demo\py_class_demo.py", line 10, in <module>
print(class_demo.__private_variable);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Class_Demo' object has no attribute '__private_variable'. Did you mean: '_protected_variable'?
通过公有方法访问变量
class Person:
def __init__(self, age, name):
self.age = age;
self.name = name;
def Say(self):
return f"Hello, my name is {self.name} and I am {self.age} years old.";
person = Person(15, "悟空");
strSay = person.Say();
print(strSay);
派生类的写法
在Python中创建派生类(也称为子类)的基本方法是使用class关键字,并在其后面写出派生类的名称,然后是括号内基类(或父类)的名称。在类定义的内部,你可以添加新属性和方法,也可以覆盖基类的方法。
代码示例
#定义基类
class BaseClass:
def __init__(self, value):
self.value = value;
self.public_variable = "Base class public variable.";
def show_value(self):
print(f"The value is {self.value}.");
#定义派生类
class DerivedClass(BaseClass):
def __init__(self, value, extra_value):
#调用基类的构造方法
super().__init__(value);
#添加额外的属性
self.extra_value = extra_value;
#覆盖基类的方法
def show_value(self):
#调用基类的方法
super().show_value();
#添加额外的打印
print(f"The extra value is {self.extra_value}.");
print(self.public_variable);
derived_class = DerivedClass("base", "derived");
derived_class.show_value();
输出
The value is base.
The extra value is derived.
Base class public variable.
备注 派生类可以继承基类的所有属性和方法,并可以根据需要添加新的功能。
- 使用
super()
函数是调用基类方法的推荐方式,特别是在涉及多重继承时。 - 使用
self
访问基类的属性,需要注意的是在派生类中不能访问基类的私有属性(私有变量)。