j-grimwood
j-grimwood

Reputation: 361

Python OOP: Are all self."something" attributes in __init__ available to other class methods?

Simple, silly question. But say I had

class Stuff:

    def __init__(self, name):

        self.name = name:

    def get_name(self):

        print(name)

new_name = Stuff(name = "Richard")
new_name.get_name()

Would this work? Would get_name be able to access the name attribute and print it out?

I can't get this code to work...

Upvotes: 2

Views: 43

Answers (1)

Andrew Hare
Andrew Hare

Reputation: 351466

There are a few things that you need to change but this works:

class Stuff:
    def __init__(self, name):
        self.name = name

    def get_name(self):
        print(self.name)

new_name = Stuff(name = "Richard")
new_name.get_name()

Besides a few syntax errors (class needs to be lowercase and some missing :) the main thing you were missing was accessing name by means of the self identifier. Since name is defined on the class you need to access it via self.

Upvotes: 5

Related Questions