python --- 类与对象(二)

类属性与方法

类的私有属性

__private_attrs:两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs。

类的方法

在类的内部,使用 def 关键字来定义一个方法,与一般函数定义不同,类方法必须包含参数 self,且为第一个参数,self 代表的是类的实例。

self 的名字并不是规定死的,也可以使用 this,但是最好还是按照约定是用 self。

类的私有方法

__private_method:两个下划线开头,声明该方法为私有方法,只能在类的内部调用 ,不能在类的外部调用。self.__private_methods。

实例

类的私有属性实例如下:

复制代码
class Person:
    name = ''
    __nickname = ''

    def __init__(self, name, nickname):
        self.name = name
        self.__nickname = nickname

    def say_hello(self):
        print("你好,我叫:" + self.name + ",我的外号是:" + self.__nickname)


person = Person('张三', '狗剩子')
person.say_hello()
print("大名叫:" + person.name)
# 报错,私有属性不能在类外部使用
print("外号叫:" + person.__nickname)

执行以上程序输出结果为:

复制代码
Traceback (most recent call last):
你好,我叫:张三,我的外号是:狗剩子
  File "F:/Python教程/project2/com/bjsxt/mypy/面向对象-对象.py", line 191, in <module>
大名叫:张三
    print("外号叫:" + person.__nickname)
AttributeError: 'Person' object has no attribute '__nickname'

类的私有方法实例如下:

复制代码
class Person:
    name = ''
    __nickname = ''

    def __init__(self, name, nickname):
        self.name = name
        self.__nickname = nickname

    def say_hello(self):
        print("你好,我叫:" + self.name + ",我的外号是:" + self.__nickname)

    def __say_hello(self):
        return self.__nickname

    def say_hello2(self):
        print(self.__nickname)


person = Person('张三', '狗剩子')
person.say_hello()
print("大名叫:" + person.name)
# 报错,私有属性不能在类外部使用
# print("外号叫:" + person.__nickname)
person.say_hello2()
# 报错,不允许在类外部调用私有方法
person.__say_hello()

以上实例执行结果:

复制代码
Traceback (most recent call last):
  File "F:/Python教程/project2/com/bjsxt/mypy/面向对象-对象.py", line 219, in <module>
    person.__say_hello()
你好,我叫:张三,我的外号是:狗剩子
AttributeError: 'Person' object has no attribute '__say_hello'
大名叫:张三
狗剩子

类的专有方法:

init : 构造函数,在生成对象时调用

del : 析构函数,释放对象时使用

add: 加运算

sub: 减运算

mul: 乘运算

truediv: 除运算

mod: 求余运算

pow: 乘方

复制代码
class User:

    def __new__(cls, *args, **kwargs):
        """
        如果 __new__方法不返回值(或者说返回 None)
        __init__ 将不会得到调用
        因为实例对象都没创建出来,调用 init 也没什么意义。
        :param args:
        :param kwargs:
        :return:
        """
        print("调用了__new__方法")
        # 返回一个实例对象,这个实例对象会传递给 __init__ 方法中定义的 self 参数
        # 以便实例对象可以被正确地初始化。
        return super(User, cls).__new__(cls)

    def __init__(self, age, name):
        """
        python 规定,__init__只能返回 None 值
        __init__方法中除了self之外定义的参数,
        都将与 __new__方法中除cls参数之外的参数是必须保持一致或者等效。
        """
        self.name = name
        self.age = age
        print("生成对象时调用")

    def __del__(self):
        print("析构函数,释放对象时调用")

    def showparams(self):
        print(self.__dict__)


user = User(age=25, name='张三')

输出结果:

复制代码
调用了__new__方法
生成对象时调用
析构函数,释放对象时调用

运算符重载

Python同样支持运算符重载,我们可以对类的专有方法进行重载,实例如下:

复制代码
class Vector:

    xpos = 0
    ypos = 0

    def __init__(self, xpos, ypos):
        self.xpos = xpos
        self.ypos = ypos

    def __add__(self, other):
        return Vector(self.xpos + other.xpos, self.ypos + other.ypos)

    def __str__(self):
        return "横坐标:" + str(self.xpos) + ";纵坐标:" + str(self.ypos)

    def __sub__(self, other):
        return Vector(self.xpos - other.xpos, self.ypos - other.ypos)

    def __mul__(self, other):
        return Vector(self.xpos * other.xpos, self.ypos * other.ypos)

    def __truediv__(self, other):
        return Vector(self.xpos / other.xpos, self.ypos / other.ypos)

    def __mod__(self, other):
        return Vector(self.xpos % other.xpos, self.ypos % other.ypos)

    def __pow__(self, power, modulo=None):
        return Vector(self.xpos ** power, self.ypos ** power)


v1 = Vector(1, 3)
v2 = Vector(4, 5)

v = v1 + v2
print(v)

v = v1 - v2
print(v)

v = v1 * v2
print(v)

v = v1 / v2
print(v)

v = v1 % v2
print(v)

v = v1 ** 2
print(v)

以上代码执行结果如下所示:

复制代码
横坐标:5;纵坐标:8
横坐标:-3;纵坐标:-2
横坐标:4;纵坐标:15
横坐标:0.25;纵坐标:0.6
横坐标:1;纵坐标:3
横坐标:1;纵坐标:9
相关推荐
im_AMBER7 分钟前
学习日志05 python
python·学习
大虫小呓12 分钟前
Python 处理 Excel 数据 pandas 和 openpyxl 哪家强?
python·pandas
哪 吒24 分钟前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
-凌凌漆-27 分钟前
【Qt】QStringLiteral 介绍
开发语言·qt
程序员爱钓鱼27 分钟前
Go语言项目工程化 — 常见开发工具与 CI/CD 支持
开发语言·后端·golang·gin
军训猫猫头1 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
真的想上岸啊1 小时前
学习C++、QT---18(C++ 记事本项目的stylesheet)
开发语言·c++·学习
明天好,会的1 小时前
跨平台ZeroMQ:在Rust中使用zmq库的完整指南
开发语言·后端·rust
摸爬滚打李上进1 小时前
重生学AI第十六集:线性层nn.Linear
人工智能·pytorch·python·神经网络·机器学习
丁劲犇2 小时前
用 Turbo Vision 2 为 Qt 6 控制台应用创建 TUI 字符 MainFrame
开发语言·c++·qt·tui·字符界面·curse