一般类功能 [英] general class functions

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

问题描述

在我的项目中,我有几十个相似的类,每个类中有数百个

描述变量。在下面的说明性示例中,我
有一个包含Nation类列表的Library类。在一个

的情况下,我可能想要一个只有国家/地区的图书馆类,并且

大陆变量欧洲,所以我会做像

library.getContinent(''Europe'')将返回一个只有欧洲国家的Library()实例

。同样,我也想要一个只有''小'国家的图书馆()

实例。


我的问题如下:有没有办法我可以为

获取具有我特定条件的子类的一般函数吗?例如,我可以通过等价测试或其他类似的方式通过
吗?我有数百个变量,比如国家,大陆等,并且确实想要

写一个单独的get ______。每个人的功能。


这让我和我一起工作的每个人都感到难过。帮助会很大

赞赏!!


#!/ usr / bin / python

类库:

def __init __(self,list = None):

self.list = list

def add(self,nation):

尝试:self.list.append(国家)

除外:self.list = [国家]

def defineNation(自我,名称,大陆,大小):

nation = Library.Nation()

nation.name = name

nation.continent = continent

nation.size =尺寸

self.add(国家)

def getContinent(自我,大陆):

library = Library()

for nation in self.list:

if nation.isContinent(continent)== True:

library.add(national)

返回图书馆

def getSize(self,size):

library = Library()

for country in self.list:

如果nation.isSize(size)== True:

library.add(国家)

返回库

def getNameList (个体经营):

outList = []

for sel f.list:

outList.append(nation.name)

return outList

class Nation:

def __init __(self,name = None,continent = None,size = None):

self.name = name#eg,Spain

self.continent = continent#eg,eg欧洲

self.size = size#eg,medium

def isContinent(self,continent):

if self.continent == continent:返回True

else:return False def isSize(self,size):

if self.size == size:return true

else:返回False


library =图书馆()

library.defineNation(''西班牙'',''欧洲'',''中'')

library.defineNation(''USA'',''NorthAmerica'',''large'')

library.defineNation(''Luxembourg'',''Europe '',''小'')

library.defineNation('''葡萄牙'',''欧洲'',''中'')


print library.getNameList()

print library.getContin ent(''Europe'')。getNameList()

print library.getContinent(''Europe'')。getSize(''small'')。ge tNameList()

解决方案

syd写道:

在我的项目中,我有几十个相似的类,里面有数百个
描述变量每。在下面的说明性示例中,我有一个包含Nation类列表的Library类。在一个
的情况下,我可能想要一个仅具有
大陆变量Europe的国家的图书馆类,所以我会做类似
library.getContinent(''欧洲''将返回一个只有欧洲国家的图书馆()实例。同样,我也可能想要一个只有''小'国家的Library()
实例。

我的问题如下:有没有办法可以为

您可以使用getattr按名称读取Nation属性。将此

方法添加到库中:

def getMatches(self,attribute,value):

library = Library()

for nation in self.list:

if getattr(national,attribute)== value:

library.add(national)

返回图书馆


现在你可以打电话给

print library.getMatches(''continent'',''Europe'')。getNameList()

print library.getMatches(''continent'',''Europe'')。getMatches(''size'',

''small'')。getNameList()


这就是你想要的吗?

肯特

这让我和我合作的每个人都感到难过。帮助会非常感激!!

#!/ usr / bin / python
类库:
def __init __(self,list = None):
self.list = list
def add(self,nation):
尝试:self.list.append(国家)
除了:self.list = [国家]
def defineNation(self,name,continent,size):
nation = Library.Nation()
nation.name = name
nation.continent = continent
nation.size = size
self.add(民族)
def getContinent(自我,大陆):
library = Library()
for nation in self.list:
if nation.isContinent (大陆)==真:
library.add(国家)
返回库
def getSize(自我,大小):
library = Library()
for nation在self.list:
如果nation.isSize(size)== True:
library.add(国家)
返回库
def getNameList(self):
outList = []
用于self.list中的国家:
outList.append(国家。姓名)
return outList
class Nation:
def __init __(self,name = None,continent = None,size = None):
self.name = name#eg,Spain
self.continent = continent#eg,Europe
self.size = size#eg,medium
def isContinent(self,continent):
if self.continent == continent:返回True
else:返回False def isSize(self,size):
如果self.size == size:return true
else:return False

library =图书馆()
library.defineNation(''西班牙'',''欧洲'',''中'')
library.defineNation(''USA'',''NorthAmerica'',' 'large'')
library.defineNation(''Luxembourg'',''Europe'',''small'')
library.defineNation(''Portugal'',''Europe'' ,''''''
打印library.getNameList()
print library.getContinent(''Europe'')。getNameList()
print library.getContinent(' 欧洲'')。getSize(''small'')。ge tNameList()



2004年11月1日17:09:53 -0800,< a href =mailto:sy ********* @ gmail.com> sy ********* @ gmail.com (syd)写道:
< blockquote class =post_quotes>我的问题如下:有没有办法可以为我的特定标准获取子类的一般功能?例如,我可以通过等效性测试或类似的测试吗?我有数百个变量,如国家,大陆等,并且确实想要单独写一个get ______。每个函数。




将以下方法添加到库


def __getattr __(self,name):

如果name.startswith(" get_"):

attrname = name [4:]

def filter(value):

library = Library()

for country in self.list:

if getattr(nation,attrname)== value:

library .add(国家)

返回库

返回过滤器

else:

返回self .__ dict __ [name]


你可以写


L.get_continent(''Europe'')。get_size(''small'')


因为任何以get _...开头的东西都是将是动态生成的
过滤函数,该函数看起来与某个属性的精确匹配相同。不需要

getContinent,getSize,isContinent和isSize。


HTH

Andrea




" syd" < SY ********* @ gmail.com>在消息中写道

新闻:a7 ************************** @ posting.google.c om ...

非常感谢Andrea和Kent!

要将我当前代码中的调用更改保持在最低限度,我希望我能编码Andrea 正在飞行获得功能。我将Andrea的
__getattr__添加到我的Library()类中,用几个国家填充了这个类,并尝试了:

library.get_continent(''Europe'')



此行创建并返回Library的实例。我假设您在python会话中导入了
导入foo然后执行了该行。

导致调用Library .__ repr __(),这是未定义的。首先是

all,我建议你将类库改为对象的子类。那是'

一般的好习惯,在这种情况下它会给你一个默认的
__repr __()方法。但那可能不是你想要的。你可能想要的是b $ b你还想要使用如下行:

print library.getContinent(''Europe'')。getNameList()

否则,library.get_continent(''Europe'')将打印如下内容:

< __ main __。库文件对象位于0x00A9F430>


Dan

回溯(最近一次调用最后一次):
文件"< stdin>",第1行,在?
文件" foo.py" ,第16行,在__getattr__
返回self .__ dict __ [name]
KeyError:''_ _ jpr__''

然后我注释掉第15和16行...... #else:
#return self .__ dict __ [name]

...并重新运行。
library.get_continent(''Europe'')


回溯(最近一次调用最后一次):
文件"< stdin>",第1行,在?
TypeError:''NoneType''对象不可调用

我调整了一下,但我无法深究这一点问题。我在这里看到了逻辑(这是我应该添加的精彩内容,Andrea),但我不知道出了什么问题。

想法?



In my project, I''ve got dozens of similar classes with hundreds of
description variables in each. In my illustrative example below, I
have a Library class that contains a list of Nation classes. In one
case, I might want a Library class with only Nations of with the
continent variable "Europe", and so I''ll do something like
library.getContinent(''Europe'') which will return a Library() instance
with only European nations. Similarly, I could also want a Library()
instance with only ''small'' size nations.

My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent", and so forth, and do want to
write a separate "get______" function for each.

This stumped everyone I work with. Help would be greatly
appreciated!!

#!/usr/bin/python
class Library:
def __init__(self,list=None):
self.list=list
def add(self,nation):
try: self.list.append(nation)
except: self.list=[nation]
def defineNation(self,name,continent,size):
nation=Library.Nation()
nation.name=name
nation.continent=continent
nation.size=size
self.add(nation)
def getContinent(self,continent):
library=Library()
for nation in self.list:
if nation.isContinent(continent)==True:
library.add(nation)
return library
def getSize(self,size):
library=Library()
for nation in self.list:
if nation.isSize(size)==True:
library.add(nation)
return library
def getNameList(self):
outList=[]
for nation in self.list:
outList.append(nation.name)
return outList
class Nation:
def __init__(self,name=None,continent=None,size=None):
self.name=name # eg, Spain
self.continent=continent # eg, Europe
self.size=size # eg, medium
def isContinent(self,continent):
if self.continent==continent: return True
else: return False def isSize(self,size):
if self.size==size: return True
else: return False

library=Library()
library.defineNation(''Spain'',''Europe'',''medium'')
library.defineNation(''USA'',''NorthAmerica'',''large'')
library.defineNation(''Luxembourg'',''Europe'',''small'' )
library.defineNation(''Portugal'',''Europe'',''medium'')

print library.getNameList()
print library.getContinent(''Europe'').getNameList()
print library.getContinent(''Europe'').getSize(''small'').ge tNameList()

解决方案

syd wrote:

In my project, I''ve got dozens of similar classes with hundreds of
description variables in each. In my illustrative example below, I
have a Library class that contains a list of Nation classes. In one
case, I might want a Library class with only Nations of with the
continent variable "Europe", and so I''ll do something like
library.getContinent(''Europe'') which will return a Library() instance
with only European nations. Similarly, I could also want a Library()
instance with only ''small'' size nations.

My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent", and so forth, and do want to
write a separate "get______" function for each.
You can use getattr to read the Nation attributes by name. Add this
method to Library:
def getMatches(self,attribute, value):
library=Library()
for nation in self.list:
if getattr(nation, attribute) == value:
library.add(nation)
return library

Now you can call
print library.getMatches(''continent'', ''Europe'').getNameList()
print library.getMatches(''continent'', ''Europe'').getMatches(''size'',
''small'').getNameList()

Is that what you want?
Kent

This stumped everyone I work with. Help would be greatly
appreciated!!

#!/usr/bin/python
class Library:
def __init__(self,list=None):
self.list=list
def add(self,nation):
try: self.list.append(nation)
except: self.list=[nation]
def defineNation(self,name,continent,size):
nation=Library.Nation()
nation.name=name
nation.continent=continent
nation.size=size
self.add(nation)
def getContinent(self,continent):
library=Library()
for nation in self.list:
if nation.isContinent(continent)==True:
library.add(nation)
return library
def getSize(self,size):
library=Library()
for nation in self.list:
if nation.isSize(size)==True:
library.add(nation)
return library
def getNameList(self):
outList=[]
for nation in self.list:
outList.append(nation.name)
return outList
class Nation:
def __init__(self,name=None,continent=None,size=None):
self.name=name # eg, Spain
self.continent=continent # eg, Europe
self.size=size # eg, medium
def isContinent(self,continent):
if self.continent==continent: return True
else: return False def isSize(self,size):
if self.size==size: return True
else: return False

library=Library()
library.defineNation(''Spain'',''Europe'',''medium'')
library.defineNation(''USA'',''NorthAmerica'',''large'')
library.defineNation(''Luxembourg'',''Europe'',''small'' )
library.defineNation(''Portugal'',''Europe'',''medium'')

print library.getNameList()
print library.getContinent(''Europe'').getNameList()
print library.getContinent(''Europe'').getSize(''small'').ge tNameList()



On 1 Nov 2004 17:09:53 -0800, sy*********@gmail.com (syd) wrote:

My question follows: is there a way I can make a general function for
getting a subclass with my specific criteria? For instance, can I
pass in an equivalence test or something like that? I have hundreds
of variables like "nation", "continent", and so forth, and do want to
write a separate "get______" function for each.



Adding the following method to Library

def __getattr__(self,name):
if name.startswith("get_"):
attrname = name[4:]
def filter(value):
library=Library()
for nation in self.list:
if getattr(nation,attrname) == value:
library.add(nation)
return library
return filter
else:
return self.__dict__[name]

you will be able to write

L.get_continent(''Europe'').get_size(''small'')

because for anything starting with "get_..." will be
generated on the fly a filtering function that looks
for exact match of an attribute. No need for
getContinent, getSize, isContinent and isSize.

HTH
Andrea



"syd" <sy*********@gmail.com> wrote in message
news:a7**************************@posting.google.c om...

Many many thanks, Andrea and Kent!

To keep changes to calls in my current code to a minimum, I''m hoping I
can encode Andrea''s "on-the-fly" get function. I added Andrea''s
__getattr__ to my Library() class, populated the class with a few
nations, and tried:

library.get_continent(''Europe'')


This line creates and returns an instance of Library. I assume that you
imported foo in a python session and then you executed that line. That
results in a call to Library.__repr__( ), which is not defined. First of
all, I recommend you change class Library to subclass from object. That''s
just good practice in general and in this case it will give you a default
__repr__( ) method. But that''s probably not what you want. What you
probably want is to still use a line like:
print library.getContinent(''Europe'').getNameList()
Otherwise, library.get_continent(''Europe'') is going to print something like:
<__main__.Library object at 0x00A9F430>

Dan

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "foo.py", line 16, in __getattr__
return self.__dict__[name]
KeyError: ''__repr__''

I then commented out lines 15 and 16...
#else:
#return self.__dict__[name]

... and re-ran.
library.get_continent(''Europe'')


Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: ''NoneType'' object is not callable

I tweaked a bit, but I could not get to the bottom of this problem. I
see the logic here (and it''s brilliant I should add, Andrea), but I''m
not sure what is wrong.

Ideas?



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

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