Tejas Sarade
Tejas Sarade

Reputation: 1212

Variable declared in __init__() without self

If I declare variable in __init__ without self, what happens to it. I know it is not class variable or instance variable. what is the exact term to describe it? How can I access it? What impact can it have while creating object of MyClass1.

class MyClass1:
    myname = "Class variable"
    def __init__(self):
        myname = "Instance variable???"   #Deliberately declared without self

a = MyClass1()
print(a.myname)

Upvotes: 1

Views: 3634

Answers (1)

reisdev
reisdev

Reputation: 3403

The variable myname is local to the __init__ method. Nothing will happen to the myname attribute of MyClass1. If you want to change the value of it, you should use the self.

class MyClass1:
    myname = "Class variable"
    def __init__(self):
        self.myname = "my attribute"

a = MyClass1()
print(a.myname)

Upvotes: 3

Related Questions