Round
Round

Reputation: 79

Why is this instance member not accessible after instantiation in Python?

This variable declared in the contractor does not exist after instantiation? Why?

It worked as expected if declare as a class variable.

class Apple():
    def show(self):
        print('apple')


class Basket():
    def __init__(self):
        apple = Apple()


basket = Basket()
basket.apple.show()

Output: AttributeError: 'Basket' object has no attribute 'apple'

class Apple():
    def show(self):
        print('apple')


class Basket():
        apple = Apple()


basket = Basket()
basket.apple.show()

Output: apple

This is what I expected.

apple

Upvotes: 1

Views: 342

Answers (2)

eapetcho
eapetcho

Reputation: 527

@Round: The main reason you get the AttributeError is that in your first definition, the variable apple is just a locale variable.

In order to access it, you must make it effectively an attribute of the class, that's it must be either an instance variable or class variable.

For example, in the example below:

class Apple:
    def show(self):
        print("apple")

class Basket:
    apple = Apple()
    def __init__(self):
        pass

apple is an attribute of the class Basket, in particular it is a class variable

On the other hand, in the following example:

class Apple:
    def show(self):
        print('apple')

class Basket:
    def __init__(self):
        self.apple = Apple()

apple is still an attribute of the class Basket, but specifically it is an instance variable.

Please, have a look at Class variable vs. Instance variable to grasp the difference between class and instance variables.

Upvotes: 1

iz_
iz_

Reputation: 16613

To assign to an instance variable, you need to assign to self like so:

class Basket():
    def __init__(self):
        self.apple = Apple()

Otherwise, you would just be creating a local variable within the __init__ function.

Upvotes: 4

Related Questions