Python 中定义类

简介

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访问基类的属性,需要注意的是在派生类中不能访问基类的私有属性(私有变量)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

依旧阳光的老码农

一毛一次,一次一毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值