简体   繁体   中英

Difference between Class Attributes, Instance Attributes, and Instance Methods in Python

I know similar questions to this have been asked before, but every website seems to define these things differently, and I am trying to follow along the official documentation: From what I understand so far:
- Class attributes are everything listed in the class Classname: code block, including the variable declarations above the __init__ functions, static methods, class methods, and methods involving instances with self
link for more info: https://docs.python.org/2/tutorial/classes.html#class-objects
- Instance attributes are both: 1.) every function listed in the class Classname: code block so everything other than the variable declarations above the __init__ function & 2.) data attributes which is when we use instance.attr and set that equal to some value
link for more info: https://docs.python.org/2/tutorial/classes.html#instance-objects

Assuming everything I wrote above is correct, I would say an Instance method is any function in the class Classname: code block since we can apply each method to the instance objects or it could just be the functions that involve self

I'm not sure what I'm understanding incorrectly, but the terminology of the python documentation is totally different from the other sites I've seen. Any help would be greatly appreciated. Thanks!

To answer this question, you need to first think about how python looks up attributes. I'll assume you know what an instance is. As a refresher. . .

class SomeClass(object):

    class_attribute = 'This -- Defined at the class level.'

    def __init__(self):
        self.instance_attribute = 'This -- Defined on an instance.'

    def method(self):
        pass

instance = SomeClass()

Class attributes are defined at the class level. Instance attributes are defined at the instance level (usually via self.xyz = ... ). Instance attributes can also be monkey patched onto the instance:

instance.another_instance_attribute = '...'

Notice that class attributes can be looked up on an instance if an instance attribute doesn't "shadow" it.

print(instance.class_attribute)

Now for methods. Methods are another animal entirely.

SomeClass.method

is definitely an attribute on the class.

instance.method

is a bit trickier to classify. Actually, when python sees that statement, it actually executes the following:

SomeClass.method.__get__(instance, SomeClass)

Weird. So what is happening here is that functions are descriptors . Since they have a __get__ method, it gets called and the return value (in this case) is a new function that knows what self is. The normal terms are "instance method" and "bound method". I suppose some might consider it an instance attribute, but, I'm not sure that's exactly correct (even though you access it via the instance)

Class attributes are same for all instances of class whereas instance attributes is particular for each instance. Instance attributes are for data specific for each instance and class attributes supposed to be used by all instances of the class.

"Instance methods" is a specific class attributes which accept instance of class as first attribute and suppose to manipulate with that instance.

"Class methods" is a methods defined within class which accept class as first attribute not instance (that's why the are class methods).

You can easily see class attributes by accessing A.__dict__ :

class A:
   class_attribute = 10
   def class_method(self):
       self.instance_attribute = 'I am instance attribute'

print A.__dict__
#{'__module__': '__main__', 'class_method': <function class_method at 0x10978ab18>, 'class_attribute': 10, '__doc__': None}

And instance attributes as A().__dict__ :

a = A()
a.class_method()
print a.__dict__
# {'instance_attribute': 'I am instance attribute'}

Some useful links from official python documentation and SO, which i hope won't confuse you more and give clearer understanding...

Class attributes- are everything listed in the class Classname: code block, It can be above or below of any method.

Instance attribute - which is created by using instance.attr or self.attr(here self is instance object only)

class Base:
  cls_var = "class attribute"
  def __init__(self):
    self.var = "instance attribute"
  def method(self):
    self.var1 = "another instance attribute"
  cls_var1 = "another class attribute"

Class attributes and instance objects - You can consider class object as a parent of all of its instance objects. So instance object can access attribute of class object.However any thing defined under class body is class attribute only.

class Base:
  cls_var = "class attribute"
  def __init__(self):
    self.var = "instance attribute"
b = Base()
print b.var                                     # it should print "instance attribute"
print b.cls_var                                 # it should print "class attribute"
print Base.cls_var                              # it should print "class attribute"
b.cls_var = "instance attribute"
print Base.cls_var                            # it should print "class attribute"
print b.cls_var                                # it should print "instance attribute"

Instance Method - Method which is created by def statement inside class body and instance method is a Method which first argument will be instance object(self). But all instance methods are class attributes, You can access it via instance object because instances are child of class object.

>>> class Base:
    def ins_method(self):
        pass


>>> b = Base()
>>> Base.__dict__
{'__module__': '__main__', '__doc__': None, 'ins_method': <function ins_method at 0x01CEE930>}
>>> b.__dict__
{}

You can access instance method by using class object by passing instance as it's first parameter-

Base.ins_method(Base())

You can refer these two articles written by me on same topic which has explanation with diagrams and post me your query - http://www.pythonabc.com/python-class-easy-way-understand-python-class/ http://www.pythonabc.com/instance-method-static-method-and-class-method/

You seem to have a pretty decent grasp of the concepts. It's hard to find information that is explained in a universal manner, especially with such a widely-used language like python. I am mostly going to echo your correct assumptions, with a few minor tweaks along the way.

Class Attributes are characteristics that all objects that will be created from the Class share. For example, if we were defining a clock Class, we would define a Class Attribute as the total number of possible hours in the clock.

class Clock:
    class_hours = 12

It is shared by all instances of the Class and can be accessed by any of the instances for reference purposes.

Class Instances are the actual data we use to define individual charactaristics of an Object created from the class. Again using the clock Class example, this would be the actual hour we set the clock to when creating a clock in a line of code (and we can also reference our Class Attribute to make sure it is within acceptable parameters):

class Clock:
    class_hours = 12

    def __init__(self, hours):
        if (hours <= class_hours):
            self.hours = hours

Keep in mind, it's not good practice to use if statements within constructors, but this is for example's sake. If you really wanted to implement this example, you would use an Instance Method to assure the hour is within defined boundaries.

Instance Methods are methods we define within the class that can manipulate the Class Instance data we define within the constructor. Going back to the clock example again, we can define a method that changes the hour, minute, or second of the clock:

class Clock:
    class_hours = 12
    class_minutes = 60
    class_seconds = 60

    def __init__(self, hours, minutes, seconds):
        self.hours = hours
        self.minutes = minutes
        self.seconds = seconds

    def setTime(new_hour, new_minute, new_second):
        self.hours = new_hour
        self.minutes = new_minute
        self.seconds = new_second

This allows us to change the instance of the clock we have already created somewhere in our code. For example, calling clock.setTime(11,49,36) would set that particular instance of clock to 11:49:36.

I hope this has been helpful and as clear as possible for you. If I was ambiguous or glossed over any terminology you don't understand, please let me know so I can update my answer to be as clear as possible.

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