PineappleLord PineappleLord - 2 months ago 22
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): = name

but why is it different to this?

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

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


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

The statements are entirely different: = 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 =

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 == is the equivalent of == 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.