Sobes.tech
Middle

How to call each method of class A?

sobes.tech AI

Answer from AI

Suppose we have a class A with methods:

import time

class A:
    def what_time(self):
        return f'{time.time()}'

    @property
    def useless_getter(self):
        return self.text

    def __private_or_public(self):
        return 1

    def __str__(self):
        return self.text

    def __init__(self, text):
        self.text = text

To call each method:

  • what_time — a regular method, called through an instance:

    a = A('hello')
    print(a.what_time())
    
  • useless_getter — a property, called as an attribute without parentheses:

    print(a.useless_getter)
    
  • __private_or_public — a method with double underscores, name mangled to change its name, called as:

    print(a._A__private_or_public())
    
  • __str__ — a special method, called automatically when converting to a string:

    print(str(a))
    

Thus, to call a private method with double underscores, you need to use the name with the class: _A__private_or_public().

How to call each method of class A? — QA / QA… - sobes.tech