关于Python中的类和OOP [英] About classes and OOP in Python

查看:59
本文介绍了关于Python中的类和OOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,


我一直想知道为什么Python处理类和OOP

的方式。根据我的理解,在Python中没有类的概念,即没有像私有变量这样的东西。任何

部分代码都允许访问任何类中的任何变量,并且

甚至可以访问不存在的变量:它们只是简单地创建。

我想知道这背后的哲学是什么,以及在未来的Python版本中是否会改变这种行为。


在我看来,很难在很大程度上使用OOP
Python代码,因为该语言的这些功能会引入许多

无意中的错误。例如,如果程序员在作业中输入变量名称

,则作业可能不会执行

程序员的意图。


Ruby对此做了一些事情,我认为在Python中包含

非常好(当然还有一些语法更改)。如果私有

变量需要一个setter / getter对,我们可以用一些

方式快捷方式,即(伪代码):


class PythonClass:

private foo =" bar"

private var = 42

allow_readwrite([foo,var])


或者allow_read只允许只读访问。也可能有一种

的方式来实现定制的getter和setter,你需要的时间

来修改输入或者其他东西:


class PythonClass:

def get foo():

return" bar"

def set var(value):

var = value


无论如何,这些只是一些猜测建议。我的主要问题

是为什么Python选择使用这种类型的OOP模型,如果它计划改变



谢谢!

解决方案

您也可以在Python中执行此操作。查看内置的物品

功能。可以使用get,set和delete

方法声明属性。这是一个只读属性的小例子。


class Test(对象):

def getProperty(self):

返回0;


prop = property(fget = getProperty)


t =测试()


print t.prop

t.prop = 100#这将失败


" fyhuang" < FY ***** @ gmail.com>写道:

我一直想知道为什么Python处理类和OOP的方式。据我所知,Python中没有类封装的概念,即没有私有变量。任何部分代码都可以访问任何类中的任何变量,甚至可以访问非存在的变量:它们只是简单地创建。
我想知道什么是哲学这背后是,如果这个行为将在未来的Python版本中发生变化。


C ++ / Java样式封装有优点和缺点

使用私有数据。你(显然)已经知道的优点。

的缺点是增加了复杂性。有一种说法,你不能在你从未写过的代码行中有一个错误

。通过编写所有这些getter

和setter方法,你只需增加批量和复杂性。


话虽如此,你确实可以在Python中拥有私有数据。只需用两个下划线(即__foo)作为变量名的前缀

,它们就会有效地将
变为私有。是的,如果你真的想要,你可以绕过这个,但是再次再次使用
,你也可以在C ++中绕过私有。您还可以通过为您的类编写__getattr __()和

__setattr __()方法来拦截任何

尝试访问Python属性。

似乎对我来说,很难在Python代码中广泛使用OOP,因为这些语言的特性引入了许多无意的错误。例如,如果程序员在作业中输入一个变量名称
,则该作业可能不会执行
程序员的意图。


是的,这是一种风险。大多数人通过进行大量的测试来处理这种风险(无论如何你都应该这样做)。如果你真的想,你可以使用__slots__技术来防止这个特殊的bug发生

(虽然纯粹主义者会告诉你这不是__slots__

的设计用于)。

我的主要问题是为什么Python选择使用这种类型的OOP模型以及是否计划更改。



听起来你已经习惯了像C ++和Java这样的东西,这些东西非常简单。一切都是在编译时声明的,并且语言中有许多保护措施可以让你在

英尺内拍摄自己。他们的问题是,他们经常阻止你获得任何有用的工作

;你花了大部分时间编写语言,而不是你想要解决的问题。


过去一周,我有两个与人们讨论细微差别

的C ++赋值运算符。我们的客户都没有给出两个关于

赋值运算符的无花果。让它们正确只是绕道而行我们需要花费多少b $ b来防止我们的软件崩溃。使用Python,我写了一个= b并且信任

它做对了。这让我可以集中精力增加价值

我们的客户会看到。


Em Seg,2006-04-10?* s 07:19 -0700,fyhuang escreveu:

class PythonClass:
private foo =" bar"
private var = 42
allow_readwrite([foo,var])


你知道foo和var会变成类变量,而不是
实例变量,对吗?


但是你可以随时做:


类PythonClass(对象):

def __init __(自我):

self .__ foo = bar


foo = property(lambda self:self .__ foo)

然后:

a = PythonClass()
a.foo
''bar''a.foo =''baz''
回溯(最近一次调用最后一次):

文件"< stdin>",第1行,在?

AttributeError:不能设置为致敬

但你也可以绕过这个安全:

a._PythonClass__foo =''baz''
a.foo



''baz''

但这不是一个错误,没有人误写_PythonClass __。

或者allow_read只允许只读访问。还有一种方法可以实现自定义getter和setter,以便你想要修改输入或者其他东西:

类PythonClass:
def get foo( ):
返回bar

def set var(value):
var = value




那里'某个PEP在某个地方提出了类似的事情(比较早些时候我给了
):


类PythonClass(对象):

def __init __(self):

self .__ foo =" bar"


创建属性foo:

def get(自我):

返回自我.__ foo


-

Felipe。


Hello all,

I''ve been wondering a lot about why Python handles classes and OOP the
way it does. From what I understand, there is no concept of class
encapsulation in Python, i.e. no such thing as a private variable. Any
part of the code is allowed access to any variable in any class, and
even non-existant variables can be accessed: they are simply created.
I''m wondering what the philosophy behind this is, and if this
behaviour is going to change in any future release of Python.

It seems to me that it is difficult to use OOP to a wide extent in
Python code because these features of the language introduce many
inadvertant bugs. For example, if the programmer typos a variable name
in an assignment, the assignment will probably not do what the
programmer intended.

Ruby does something with this that I think would be excellent as an
inclusion in Python (with some syntax changes, of course). If private
variables require a setter/getter pair, we can shortcut that in some
way, i.e. (pseudocode):

class PythonClass:
private foo = "bar"
private var = 42
allow_readwrite( [ foo, var ] )

Or allow_read to only allow read-only access. Also there might be a
way to implement custom getters and setters for those times you want
to modify input or something:

class PythonClass:
def get foo():
return "bar"

def set var( value ):
var = value

Anyways, these are just some speculatory suggestions. My main question
is that of why Python chooses to use this type of OOP model and if it
is planned to change.

Thanks!

解决方案

You can do this in Python as well. Check out the property built-in
function. One can declare a property with a get, set, and delete
method. Here''s a small example of a read-only property.

class Test(object):
def getProperty(self):
return 0;

prop = property(fget = getProperty)

t = Test()

print t.prop

t.prop = 100 # this will fail


"fyhuang" <fy*****@gmail.com> wrote:

I''ve been wondering a lot about why Python handles classes and OOP the
way it does. From what I understand, there is no concept of class
encapsulation in Python, i.e. no such thing as a private variable. Any
part of the code is allowed access to any variable in any class, and
even non-existant variables can be accessed: they are simply created.
I''m wondering what the philosophy behind this is, and if this
behaviour is going to change in any future release of Python.
There are advantages and disadvantages to C++/Java style encapsulation
using private data. The advantages you (apparently) already know. The
disadvantage is added complexity. There''s a saying, "You can''t have a bug
in a line of code you never write". By having to write all those getter
and setter methods, you just add bulk and complexity.

That being said, you can indeed have private data in Python. Just prefix
your variable names with two underscores (i.e. __foo), and they effectively
become private. Yes, you can bypass this if you really want to, but then
again, you can bypass private in C++ too. You can also intercept any
attempt to access Python attributes by writing __getattr__() and
__setattr__() methods for your class.
It seems to me that it is difficult to use OOP to a wide extent in
Python code because these features of the language introduce many
inadvertant bugs. For example, if the programmer typos a variable name
in an assignment, the assignment will probably not do what the
programmer intended.
Yes, that is is a risk. Most people deal with that risk by doing a lot of
testing (which you should be doing anyway). If you really want to, you can
use the __slots__ technique to prevent this particular bug from happening
(although the purists will tell you that this is not what __slots__ was
designed for).
My main question is that of why Python chooses to use this type of OOP
model and if it is planned to change.



It sounds like you are used to things like C++ and Java, which are very
static languages. Everything is declared at compile time, and there are
many safeguards in the language to keep you from shooting yourself in the
foot. They problem is, they often prevent you from getting any useful work
done either; you spend most of your time programming the language, not the
problem you are trying to solve.

In the past week, I''ve had two conversations with people about the nuances
of C++ assignment operators. None of our customers give two figs about
assignment operators. Getting them right is just a detour we need to take
to keep our software from crashing. With Python, I write a = b and trust
that it does the right thing. That lets me concentrate on adding value
that our customer will see.


Em Seg, 2006-04-10 ?*s 07:19 -0700, fyhuang escreveu:

class PythonClass:
private foo = "bar"
private var = 42
allow_readwrite( [ foo, var ] )
You are aware that foo and var would become class-variables, not
instance-variables, right?

But you can always do:

class PythonClass(object):
def __init__(self):
self.__foo = "bar"

foo = property(lambda self: self.__foo)
And then:

a = PythonClass()
a.foo ''bar'' a.foo = ''baz'' Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: can''t set attribute
But you can also bypass this "security":
a._PythonClass__foo = ''baz''
a.foo


''baz''
But this was not a mistake, nobody mistakenly writes "_PythonClass__".
Or allow_read to only allow read-only access. Also there might be a
way to implement custom getters and setters for those times you want
to modify input or something:

class PythonClass:
def get foo():
return "bar"

def set var( value ):
var = value



There''s a PEP somewhere that proposes things like (same example I gave
earlier):

class PythonClass(object):
def __init__(self):
self.__foo = "bar"

create property foo:
def get(self):
return self.__foo

--
Felipe.


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

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