How to add a methods attribute if its not in __init__

910 views python

I am just learning classes and am having a hard time understanding how to add an attribute to a method that isnt __init__ from an outside function .

for example

class Year:
    def __init__(self):
        self._list = []
    def add_year(self,year):
        self._year = year
def main():
    year = 1998
    #how do I get this year into the year class to add to list?

answered question

You must first create a Year object and then call its method add_year().

3 Answers


Below is one example see if helps you

class Dog:

    # Class Attribute
    species = 'mammal'

    # Initializer / Instance Attributes
    def __init__(self, name, age): = name
        self.age = age

    # instance method
    def description(self):
        return "{} is {} years old".format(, self.age)

    # instance method
    def speak(self, sound):
        return "{} says {}".format(, sound)

# Instantiate the Dog object
mikey = Dog("Mikey", 6)

# call our instance methods
print(mikey.speak("Gruff Gruff"))

The output is as below.

Mikey is 6 years old
Mikey says Gruff Gruff

if you want to learn more about object-oriented way programming in python follow the below tutorial - [][1]

posted this

As mentioned in the comment above:

Create an instance:

yobj = Year()

and pass the value to be assigned

year = 1998

posted this

The method __init__ has nothing special except that it is executed when you instantiate an object. This means, you could assign or get an attribute to an instance of Year pretty much anywhere in your code, not only in __init__.

class Year:
    def __init__(self):
        # You can define an attribute in __init__
        self.year_list = []

    def add_year(self, year):
        # You can define and access an attribute in any method
        self.last_year_added = year

def main():
    year = 1998

    # You must instantiate a Year first
    my_year = Year()

    # Then execute the method add_year
    my_year.add_year(year + 1)

    print(my_year.year_list)  # [1998, 1999]
    print(my_year.last_year_added) # 1999

    # Note that you can even add attribute outside methods
    my_year.month = 'December'

    print(my_year.month) # December


posted this

Have an answer?


Please login first before posting an answer.