在 Python 中将类属性作为该类的函数的参数传递 [英] Pass class attribute as parameter of a function of that class in Python

查看:36
本文介绍了在 Python 中将类属性作为该类的函数的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所示,我试图将我的类的一个属性作为同一个类的函数的参数传递.在下面的示例中,print_top_n() 的功能是默认打印 self.topn,但如果需要,也可以使用不同的值调用该函数.这是 Python(或一般编程)犯规还是有办法做到这一点?

<预><代码>>>>类示例():def __init__(self, topn=5):self.topn = topndef print_top_n(self, n=self.topn):打印 n回溯(最近一次调用最后一次):文件<pyshell#7>",第 1 行,在 <module> 中类示例():示例中的文件<pyshell#7>",第 4 行def print_top_n(self, n=self.topn):NameError: 名称 'self' 未定义

解决方案

方法是在类创建时创建,方法创建时设置默认值(见这个问题/答案) -- 在调用函数时不会重新计算它们.换句话说,这一切发生在 self 被创建之前很久(因此是 NameError).

典型的方法是使用可以在 print_top_n 内部检查的标记值(None 是最常见的).

def print_top_n(self, n=None):n = self.topn 如果 n 是 None else n打印 n

As the title indicates, I am trying to pass an attribute of my class as a parameter for a function of that same class. In the example below, the functionality of print_top_n() would be to print self.topn by default, but the function could also be called with a different value if need be. Is this a Python (or general programming) foul or is there a way to do this?

>>> class Example():
    def __init__(self, topn=5):
        self.topn = topn
    def print_top_n(self, n=self.topn):
        print n



Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    class Example():
  File "<pyshell#7>", line 4, in Example
    def print_top_n(self, n=self.topn):
NameError: name 'self' is not defined

解决方案

The methods are created when the class is created, and the default values are set when the method is created (See this question/answer) -- They aren't re-evaluted when the function is called. In other words, this all happens long before self has been created (Hence the NameError).

The typical approach is to use a sentinel value that you can check inside of print_top_n (None is the most common).

def print_top_n(self, n=None):
    n = self.topn if n is None else n
    print n

这篇关于在 Python 中将类属性作为该类的函数的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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