Pass class attribute as a function parameter of this class in Python

As indicated in the header, I am trying to pass an attribute of my class as a parameter to a function of the same class. In the example below, the functionality print_top_n()is to print self.topnby default, but if necessary, the function can also be called with a different value. Is this a Python background (or general programming) 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
0
source share
3 answers

, (. /). - " t re-evaluted . , self (, NameError).

, print_top_n (None ).

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

- -. , n=None ( api), , - n=None .

marker = object()

class Example:
    def __init__(self, topn=5):
        self.topn = topn

    def print_top_n(self, n=marker):
        if n is marker:
            n = self.topn
        print(n)
+3

; , , . :

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

Source: https://habr.com/ru/post/1671183/


All Articles