PineappleLord PineappleLord - 1 month ago 5
Python Question

Python Creating Classes Code

Sorry for the poor title, didnt know what to put.

When creating a class in python i use this,

class NewClass(object):
def __init__(self,name):
self.name = name


but why is it different to this?

class NewClass(object):
def __init__(self,name):
name = self.name


Surely the equals sign means it is the same process? Why is different?

Answer

= is an assignment statement, you appear to be confusing this with a ==, the equality comparison operator.

The statements are entirely different:

self.name = name

assigns the value referenced by the local variable name to the attribute name on the object referenced by self. It sets an attribute on the newly created instance, from the value passed into the initialiser method.

The alternative statement

name = self.name

assigns the value of the attribute name found on self, to the local variable name. It rebinds the local name (replaces the old value with a new). Once the method ends, the effects are gone. You are likely to get an AttributeError as the attribute name doesn't exist on self at that point in time.

If == had been used, then usually yes, name == self.name is the equivalent of self.name == name. However, objects can override how equality is tested by defining a new implementation for the __eq__ method so the two expressions could theoretically produce different results.

Comments