Python中的非成员函数与成员函数 [英] Non-member vs member functions in Python

查看:108
本文介绍了Python中的非成员函数与成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,努力使语言的功能与我从C ++和Java的背景中习得的习惯保持一致.

I'm relatively new to Python and struggling to reconcile features of the language with habits I've picked up from my background in C++ and Java.

与封装有关的最新问题,特别是由Meyer的"有效C ++ "的第23条总结的一个最佳想法:

The latest issue I'm having has to do with encapsulation, specifically an idea best summed up by Item 23 of Meyer's "Effective C++":

首选非-成员非朋友功能改为成员功能.

暂时忽略 friend 机制,是否也认为非成员函数比Python中的成员函数更合适?

一个强制性的asinine示例:

An obligatory, asinine example:

class Vector(object):
    def __init__(self, dX, dY):
        self.dX = dX
        self.dY = dY

    def __str__(self):
        return "->(" + str(self.dX) + ", " + str(self.dY) + ")"

    def scale(self, scalar):
        self.dX *= scalar
        self.dY *= scalar

def scale(vector, scalar):
    vector.dX *= scalar
    vector.dY *= scalar

给出 v = Vector(10,20),我们现在可以调用 v.scale(2) scale(v,2)使向量的大小加倍.

Given v = Vector(10, 20), we can now either call v.scale(2) or scale(v, 2) to double the magnitude of the vector.

考虑到我们在这种情况下使用属性这一事实,两个选项中的哪个选项(如果有)-更好,为什么?

Considering the fact that we're using properties in this case, which of the two options - if any - is better, and why?

推荐答案

有趣的问题.

与大多数Java程序员提出的问题相比,您从一个不同的地方开始,Java程序员通常会假设您在不需要时就需要类.通常,在Python中没有类是没有意义的,除非您专门进行数据封装.

You're starting from a different place than most questions coming from Java programmers, which tend to assume that you need classes when you mostly don't. Generally, in Python there's no point in having classes unless you're specifically doing data encapsulation.

当然,在您的示例中,您实际上是在这样做,因此使用类是合理的.就个人而言,我要说的是,既然您 do 有一个类,那么最好使用成员函数:您正在对该特定矢量实例进行特定的操作,因此对于该功能将成为Vector上的一种方法.

Of course, here in your example you are actually doing that, so the use of classes is justified. Personally, I'd say that since you do have a class, then the member function is the best way to go: you're specifically doing an operation on that particular vector instance, so it makes sense for the function to be a method on Vector.

如果您想使其成为独立的函数(我们不真正使用成员"或非成员"一词),则需要使它与不一定从其继承的多个类一起使用彼此或共同的基础.多亏了鸭式输入,这样做是相当普遍的做法:指定函数期望一个对象具有一组特定的属性或方法,然后对它们进行处理.

Where you might want to make it a standalone function (we don't really use the word "member" or "non-member") is if you need to make it work with multiple classes which don't necessarily inherit from each other or a common base. Thanks to duck-typing, it's fairly common practice to do this: specify that your function expects an object with a particular set of attributes or methods, and do something with those.

这篇关于Python中的非成员函数与成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆