Class 上成员和属性的迭代
Iteration on members and attributes on a Class
我了解如何根据从 Web 中挑选的示例创建一个简单的 class,但是在尝试访问其中的成员时我遇到了困难,即:
假设这是我的 class:
class Fruit(object):
def __init__(self, name, color, flavor):
self.name = name
self.color = color
self.flavor = flavor
def description(self):
print('I am a %s %s and my taste is %s and I am %s' % self.color, self.name, self.flavor))
创建对象我使用:
lemon = Fruit('lemon', 'yellow', 'sour')
并为我使用的柠檬创建一个新属性:
lemon.peel = 'easy'
我想在 class 内部(或外部)定义一个方法,该方法将被称为 printall
,它将遍历 class 的所有现有成员并打印即使属性是可变的(比最初定义的还要多),它们都具有自己的属性。我觉得这叫"overloading"
但我不确定正确的术语。
您要查找的术语 type introspection. Overloading 是完全不同的东西,您在其中提供了方法的不同实现。
您可以使用 var()
function 访问所有实例属性;它 returns 一个字典,然后你可以遍历它来打印你的变量:
def printall(self):
for name, value in vars(self).items():
print('self.{} = {!r}'.format(name, value))
也许这就是您要查找的内容,虽然 printall 方法不是 class 的一部分,但当您将对象传递给它时它能够访问 class 并且以下代码应打印 Fruits class.
中对象 lemon 的属性名称和值
def printall(lemon):
for a in dir(lemon):
if not a.startswith('__') :
print a,":",getattr(lemon, a)
#rest of the code
lemon = Fruit('lemon', 'yellow', 'sour')
lemon.peel = 'easy'
printall(lemon)
如果您不确定,可以使用下面的循环查找所有成员的详细信息
import gc
#garbage collector should do the trick
#all the other code
for obj in gc.get_objects():
if isinstance(obj, Fruit):
print "object name :",obj.name
printall(obj)
我了解如何根据从 Web 中挑选的示例创建一个简单的 class,但是在尝试访问其中的成员时我遇到了困难,即:
假设这是我的 class:
class Fruit(object):
def __init__(self, name, color, flavor):
self.name = name
self.color = color
self.flavor = flavor
def description(self):
print('I am a %s %s and my taste is %s and I am %s' % self.color, self.name, self.flavor))
创建对象我使用:
lemon = Fruit('lemon', 'yellow', 'sour')
并为我使用的柠檬创建一个新属性:
lemon.peel = 'easy'
我想在 class 内部(或外部)定义一个方法,该方法将被称为 printall
,它将遍历 class 的所有现有成员并打印即使属性是可变的(比最初定义的还要多),它们都具有自己的属性。我觉得这叫"overloading"
但我不确定正确的术语。
您要查找的术语 type introspection. Overloading 是完全不同的东西,您在其中提供了方法的不同实现。
您可以使用 var()
function 访问所有实例属性;它 returns 一个字典,然后你可以遍历它来打印你的变量:
def printall(self):
for name, value in vars(self).items():
print('self.{} = {!r}'.format(name, value))
也许这就是您要查找的内容,虽然 printall 方法不是 class 的一部分,但当您将对象传递给它时它能够访问 class 并且以下代码应打印 Fruits class.
中对象 lemon 的属性名称和值def printall(lemon):
for a in dir(lemon):
if not a.startswith('__') :
print a,":",getattr(lemon, a)
#rest of the code
lemon = Fruit('lemon', 'yellow', 'sour')
lemon.peel = 'easy'
printall(lemon)
如果您不确定,可以使用下面的循环查找所有成员的详细信息
import gc
#garbage collector should do the trick
#all the other code
for obj in gc.get_objects():
if isinstance(obj, Fruit):
print "object name :",obj.name
printall(obj)