关于使用对象的简单问题(可能是faq) [英] Simple questions on use of objects (probably faq)

查看:81
本文介绍了关于使用对象的简单问题(可能是faq)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我很难理解如何真正欣赏物品

方向。我想这些都是常见问题解答,但我无法找到

的答案。也许我的问题是我的风格和理解受到了matlab和fortran的影响。


我尝试了下面的简单示例并遇到了几个问题:

1:我为什么不能这样做:

def __init __(self,self.x):

并避免self.x = x


2:在列表中插入实例是否是一个好主意,或者是否有一种更简单的方法可以对给定类型的所有实例执行某些操作?


3:为什么我不能说并获得最大的实例属性和

的列表?

y_max = max(y []。x)和

ys = [y []。x]


4:我可以避免虚拟计数器i in for循环并做一些事情

喜欢:

yz = [y [: - 1] .xy [1:]。x]


运行的代码:


class Foo:

def __init __(self,x):

self。 x = x


y = []

y.append(Foo(10.0))

y.append(Foo(110.0) ))

y.append(Foo(60.0))

ys = []

y_max = 0.0

y_min = 0.0

for s in y:

ys.extend([sx])

y_max = max(sx,y_max)

y_min = min(sx,y_min)


yz = []

for i in range(len(ys)-1):

yz.append(ys [i +1] -ys [i])


我希望能做什么:

class Foo:

def __init __( self,self.x):

继续

y = []

y.append(Foo(10.0))

y.append(Foo(110.0))

y.append(Foo(60.0))


ys =([y []。x] )

y_max = max(y []。x)

y_min = min(y []。x)


yz = [y [: - 1] .xy [1:]。x]


-

Brian(删除邮件运动)
http://www.et.web .mek.dtu.dk / Staff / be / be.html
http://www.rugbyklubben-speed.dk

推荐答案


3:为什么我说并获得最大的实例属性和
列表? y_max = max(y []。x)和
ys = [y []。x]


y_max = max([e代表y]]


参见List comprehensions在python docs中:
http://docs.python。 org / tut / node7.htm ... 00000000000000

4:我可以在for循环中避开虚拟计数器并做一些像
这样的事情:
yz = [y [: - 1] .xy [1:]。x]
3: Why can??t I say and get the maximum of instance attributes and a
list of them?
y_max=max(y[].x) and
ys=[y[].x]
y_max = max([e.x for e in y])

See "List comprehensions" in python docs:
http://docs.python.org/tut/node7.htm...00000000000000
4: Can I avoid the dummy counter i in the for loop and do something
like:
yz=[y[:-1].x-y[1:].x]




yz = [ex for e in y]

yz.reverse()


-


|马特哈蒙德

|研发工程师,BBC Research& D;开发,Tadworth,萨里,英国。

| http://kamaelia.sf.net/

| http://www.bbc.co.uk/rd/


2006年3月8日星期三11:00:09 +0000,Matt Hammond写道:
On Wed, 08 Mar 2006 11:00:09 +0000, Matt Hammond wrote:
4:我可以在for循环中避开虚拟计数器i并做一些像
yz = [y [: - 1] .xy [1:]。x]
4: Can I avoid the dummy counter i in the for loop and do something
like:
yz=[y[:-1].x-y[1:].x]



yz = [ex for e in y]
yz.reverse()



yz = [e.x for e in y]
yz.reverse()




我不觉得' OP真正想要的是什么。他似乎把错误的切片语法用作for循环的某种奇怪的替代品。


当然,我可能是错的。

-

史蒂文。



I don''t think that''s what the O.P. actually wants. He seems to have
misused slicing syntax as some sort of weird replacement for a for loop.

Of course, I could be wrong.
--
Steven.


2006年3月8日星期三11:04:41 +0100,Brian Elmegaard写道:
On Wed, 08 Mar 2006 11:04:41 +0100, Brian Elmegaard wrote:


我正在努力去理解如何真正欣赏对象
方向。我想这些都是常见问题解答,但我无法找到答案。也许我的问题是我的风格和理解受到matlab和fortran的影响。

我尝试了下面的简单示例并遇到了几个问题:
1:为什么可以'我这样做:
def __init __(self,self.x):
并避免self.x = x


好​​的,让我们看看举个例子:


类鹦鹉:

def __init __(self,self.x):

通过


现在我们创建一个新的Parrot实例:


p = Parrot(美丽的羽毛)


会发生什么是Python创建一个Parrot实例,并使用两个参数调用

__init__方法:实例本身,称为self,

和字符串美丽的羽毛称为self.x。


除此之外,这不起作用。你不能定义一个方法或函数定义

这样:


def f(xy):#won''t work


这是一个语法错误,它需要对Python进行重大更改才能使其正常工作 - 这些变化带来了可疑的好处。

好​​吧,那么替代方案呢:


类鹦鹉:

def __init __(self,x):

#Python自动调用self.x = x,

#所以你不必。

通过


为什么Python不这样做?


答案很简单。如果你不希望x成为

实例的属性怎么办?如果你想用其他方式使用x怎么办?


class Parrot:

def __init __(self,x):

y = x.strip()

print"所有鹦鹉都有%s。 %y

self.y = y.upper()[0]
Hi,

I am struggling to understand how to really appreciate object
orientation. I guess these are FAQ''s but I have not been able to find
the answers. Maybe my problem is that my style and understanding are
influenced by matlab and fortran.

I tried with the simple example below and ran into several questions:
1: Why can''t I do:
def __init__(self,self.x):
and avoid the self.x=x
Okay, let''s look at an example:

class Parrot:
def __init__(self, self.x):
pass

Now we create a new instance of Parrot:

p = Parrot("beautiful plumage")

What happens is that Python creates a Parrot instance, and calls the
__init__ method with two arguments: the instance itself, called "self",
and the string "beautiful plumage" called "self.x".

Except, this won''t work. You can''t define a method or function definition
like this:

def f(x.y): # won''t work

This is a syntax error, and it would require significant changes to
Python to make it work -- changes which are of dubious benefit.

Okay, so what about an alternative:

class Parrot:
def __init__(self, x):
# Python automatically calls "self.x = x",
# so you don''t have to.
pass

Why doesn''t Python do this?

The answer is simple. What if you don''t want x to be an attribute of the
instance? What if you want to use x some other way?

class Parrot:
def __init__(self, x):
y = x.strip()
print "All parrots have %s." % y
self.y = y.upper()[0]
p =鹦鹉(美丽的羽毛)
所有鹦鹉都有美丽的羽毛。 py
''B''px
回溯(最近一次调用最后一次):

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

AttributeError:Parrot实例没有属性''''


一般来说,Python从不猜测你想要什么。

显式比隐式更好。如果你想要一个属性self.x,你必须为它分配
,Python不会猜测这只是因为你将一个参数x

传递给__init__它应该变成一个属性。

2:在列表中插入实例是否是一个好主意,或者是否有一种更简单的方法可以对给定类型的所有实例执行某些操作?


如果你想对一些实例做一些事情,你需要保持

以某种方式跟踪它们。你可以通过将每个实例分配给它的

自己的名字来做到这一点:


p1 = Parrot(尖锐的喙)

p2 =鹦鹉(长尾羽毛)

p3 =鹦鹉(对坚果的胃口)


或在列表中:


parrots = [Parrot(尖嘴喙),Parrot(长尾羽毛)]


或字典:


parrots = {1:Parrot(尖嘴喙),2:鹦鹉(长尾羽毛)}


或你喜欢的任何其他方式。

3:为什么我不能说并得到最大的实例属性和它们的列表?
y_max = max(y [ ] .x)和
ys = [y []。x]


如果谈论获得最大值的实例没有意义

属性。如果某些属性是数字而某些属性不是?怎么回事?
Python知道你关心哪些属性?

当然,如果你为你的课程编程,你可以这样做。


类垃圾邮件:

def __init __(self,x,y,z):

self.x = x

self.y = y + 1

self.z = 1 - z

self.args =(x,y,z)#保存参数副本


def lister(self):

#无需报告self.args

返回[self.x,self.y。 self.z]

obj =垃圾邮件(2,3,4)
obj.lister()
[2,4,-3]

现在你可以随心所欲地做任何事情:

max(obj.lister())
4分钟(obj.lister())
p = Parrot(" beautiful plumage ") All parrots have beautiful plumage. p.y ''B'' p.x Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: Parrot instance has no attribute ''x''

As a general rule, Python never guesses what you want. It is better to be
explicit than implicit. If you want an attribute self.x, you have to
assign to it, Python won''t guess that just because you pass an argument x
to __init__ that it should be turned into an attribute.
2: Is it a good idea to insert instances in a list or is there a simpler
way to do something with all instances of a given type?
If you want to do something with a number of instances, you need to keep
track of them somehow. You can do that by assigning each instance to its
own name:

p1 = Parrot("sharp beaks")
p2 = Parrot("long tail feathers")
p3 = Parrot("an appetite for nuts")

Or in a list:

parrots = [Parrot("sharp beaks"), Parrot("long tail feathers")]

or a dictionary:

parrots = {1: Parrot("sharp beaks"), 2: Parrot("long tail feathers")}

or any other way you like.
3: Why can??t I say and get the maximum of instance attributes and a
list of them?
y_max=max(y[].x) and
ys=[y[].x]
If doesn''t make sense to talk about getting the maximum of instance
attributes. What if some attributes are numbers and some are not? How does
Python know which attributes you care about?

Of course you can, if you program your class to do it.

class Spam:
def __init__(self, x, y, z):
self.x = x
self.y = y + 1
self.z = 1 - z
self.args = (x, y, z) # save a copy of the arguments

def lister(self):
# no need to report self.args
return [self.x, self.y. self.z]
obj = Spam(2, 3, 4)
obj.lister() [2, 4, -3]

Now you can do anything you want with it:
max(obj.lister()) 4 min(obj.lister())



-3

4:我可以在for循环中避开虚拟计数器i并做一些像
这样的事情:
yz = [y [: - 1] .xy [1:]。x]


可能。如果我弄清楚你想要做什么,我会回答。

运行的代码:

类Foo:
def __init __(self, x):
self.x = x

y = []
y.append(Foo(10.0))
y.append(Foo(110.0))
y.append(Foo(60.0))


好​​的,你有一个Foo实例列表。

ys = []
y_max = 0.0
y_min = 0.0
对于s中的s:
ys.extend([sx])


你不要不需要创建一个新的单项列表并调用extend

方法。请改为:


ys.append(sx)

y_max = max(sx,y_max)
y_min = min(sx,y_min)


除非你真的想看到更改时的最大值和最小值,否则这是浪费。只需在收集所有

之后调用该函数值:


y_max = max(ys)

y_min = min(ys)


yz = []
我在范围内(len(ys)-1):
yz.append(ys [i + 1] ] -ys [i])


我认为你正在创建一个首要差异列表,是吗?


你的代码应该可行,并且很好。这是另一种方式:


#使用列表理解:

yz = [ys [i + 1] - ys [i] for i in range( len(ys) - 1)]


另一个:


索引,枚举值(ys [: - 1]):

yz.append(ys [index + 1] - value)

顺便说一句,不要害羞为变量使用更有意义的名字。

ys和yz非常相似,是一个等待发生的错误。

我希望我能做什么:
Foo类:
def __init __(自我,self.x):
继续


你不能在那里继续使用,它不是空的。也许你想要

" pass"?

y = []
y.append(Foo(10.0))
y.append(Foo( 110.0))
y.append(Foo(60.0))
ys =([y []。x])
y_max = max(y []。x)
y_min = min(y []。x)

yz = [y [: - 1] .xy [1:]。x]


-3
4: Can I avoid the dummy counter i in the for loop and do something
like:
yz=[y[:-1].x-y[1:].x]
Probably. If I work out what you are trying to do, I''ll answer.
The code that runs:

class Foo:
def __init__(self,x):
self.x=x

y=[]
y.append(Foo(10.0))
y.append(Foo(110.0))
y.append(Foo(60.0))
Okay, you have a list of Foo instances.
ys=[]
y_max=0.0
y_min=0.0

for s in y:
ys.extend([s.x])
You don''t need to create a new, single item list and call the extend
method. Do this instead:

ys.append(s.x)
y_max=max(s.x,y_max)
y_min=min(s.x,y_min)
Unless you actually want to see the maximum and minimum as they change,
this is wasteful. Just call the function at the end, after collecting all
the values:

y_max = max(ys)
y_min = min(ys)

yz=[]
for i in range(len(ys)-1):
yz.append(ys[i+1]-ys[i])
I think you are creating a list of first differences, yes?

Your code should work, and is perfectly fine. Here is another way:

# use a list comprehension:
yz = [ys[i+1] - ys[i] for i in range(len(ys) - 1)]

And another:

for index, value in enumerate(ys[:-1]):
yz.append(ys[index+1] - value)
By the way, don''t be shy about using more meaningful names for variables.
ys and yz are terribly similar, and is a bug waiting to happen.
What I hoped I could do:
class Foo:
def __init__(self,self.x):
continue
You can''t use continue in there, it isn''t a null-op. Perhaps you wanted
"pass"?
y=[]
y.append(Foo(10.0))
y.append(Foo(110.0))
y.append(Foo(60.0))

ys=([y[].x])
y_max=max(y[].x)
y_min=min(y[].x)

yz=[y[:-1].x-y[1:].x]



在尝试发明捷径之前,你实际上学到了一些Python语法? [x:y]语法已经对Python有意义了,

不是你想要的。


此外,虽然Python中的所有内容都是对象,你没有*使用

面向对象技术。我建议您花一些时间在交互式解释器中使用

Python,只需处理

数字,字符串等列表,熟悉它们的工作方式,学习

语言。 help()命令非常有用,如果你没有完成教程,你应该这样做。

希望这会有所帮助,

-

史蒂文。



How about, before trying to invent short cuts, you actually learn some of
the Python syntax? The [x:y] syntax already has a meaning to Python,
just not what you want.

Also, while everything in Python is an object, you don''t *have* to use
object oriented techniques. I suggest you spend some time playing with
Python in the interactive interpreter, just doing things with lists of
numbers, strings, and so forth, getting used to how they work, learning
the language. The help() command is very useful, and if you haven''t done
the tutorial, you should.
Hope this helps,

--
Steven.


这篇关于关于使用对象的简单问题(可能是faq)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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