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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

30岁老阿姨

支持一下哦!!

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

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

打赏作者

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

抵扣说明:

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

余额充值