Home > Backend Development > Python Tutorial > How Do I Add and Access Instance Methods in Python?

How Do I Add and Access Instance Methods in Python?

Susan Sarandon
Release: 2024-12-20 17:38:10
Original
727 people have browsed it

How Do I Add and Access Instance Methods in Python?

Accessing Instance Methods

In Python, objects have two types of methods: functions and bound methods. Bound methods are associated with a specific instance, and they pass the instance as the first argument when called. Functions, on the other hand, are unbound and can be modified at any time.

To illustrate the difference:

def foo():
    print("foo")

class A:
    def bar(self):
        print("bar")

a = A()

print(foo)  # <function foo at 0x00A98D70>
print(a.bar)  # <bound method A.bar of <__main__.A instance at 0x00A9BC88>>
Copy after login

Adding Methods to Class Definitions

You can modify class definitions to add new methods for all instances. For example, the following adds a fooFighters method to the A class:

def fooFighters(self):
    print("fooFighters")

A.fooFighters = fooFighters

a2 = A()
a2.fooFighters()  # fooFighters

# Also affects previously defined instances
a.fooFighters()  # fooFighters
Copy after login

Adding Methods to Single Instances

Adding methods to individual instances is more complex. The following attempt fails because the function is not bound to the instance:

def barFighters(self):
    print("barFighters")

a.barFighters = barFighters

a.barFighters()  # TypeError: barFighters() takes exactly 1 argument (0 given)
Copy after login

To bind the function, use the MethodType function from the types module:

import types
a.barFighters = types.MethodType(barFighters, a)

a.barFighters()  # barFighters

# Other instances unaffected
a2.barFighters()  # AttributeError: A instance has no attribute 'barFighters'
Copy after login

Further exploration of descriptors and metaclass programming provides more advanced techniques for manipulating object methods.

The above is the detailed content of How Do I Add and Access Instance Methods in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template