简体   繁体   中英

do I understand the difference between instance attributes and class attributes in Python?

Let's say I have a method and a class:

def my_method(self):
    self.mark = 'Knopfler'

class MySubclass(object)
    my_method = my_method

I can think of 3 or 4 ways to use my_method within another class.

Case 1: If I want to have access to my_method within yet another class like this:

class MyClass(object):
    def __init__(self):
        self.my_subclass = MySubclass()

am I correct in thinking that this will allow me to use my_method on an instance like this:

my_inst = MyClass()
my_inst.my_subclass.my_method()

This seems to work like I expect, but if I do it like this: Case 2:

class MyClass(object):
    my_subclass = MySubclass

my_inst = MyClass()
my_inst2 = MyClass()
my_inst.my_subclass.my_method()

as I understand it, the previous line will apply my_method to both my_inst and my_inst2 . Is that correct?

Case 3: Another way to get my_method as an attribute of MyClass is:

class MyClass(object):
    my_method = my_method

and as I understand it, when I have multiple instances of MyClass, applying my_method will affect only the instance to which it is bound. Is that correct?

Case 4 (last one):

class MyClass(object):
    def __init__(self):
        self.my_method = my_method

and the problem with this final method is that it seems to create my_method as an unbound method, which does not suit my needs. Is there way to add an existing method as a bound instance method in a class definition?

Ok. That is all. Please let me know which of these four cases makes the most sense to use. Thanks.

Answering to your last case, you can bind a method to a class instance with MethodType :

import types

class MyClass(object):
    def __init__(self):
        self.my_method = types.MethodType(my_method, self)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM