Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to get variable
#1
how do I get the variable holding the data

something like this
class Student:
    def __init__(self, name):
        self.name = name
    def display(self):
        print(f'Hello! My name is: {self.name}')
    def get_var(self):
        # code that will return the variable "tim"

tim = Student('tim')
Reply
#2
Use return
    def get_var(self):
        return self.name
This does not return the variable "name", it returns the str object that self.name references. In Python, variables are just a name that provides a way to reference a value. It is kind of like a python dictionary where you have a key that you can use to retrieve a value.

There is no reason to write get_var(). If you want to get the str reverenced by "name", just use "name".
class Student:
    def __init__(self, name):
        self.name = name


tim = Student("tim")
print(tim.name)
Output:
tim
Reply
#3
i mean like this

class Food:
    def __init__(self, healthy=bool, type=str):
        self.healthy = healthy
        self.type = type
    def get_var(self):
        # code that will result in apple

apple = Food(True, 'fruit')
Reply
#4
I do not understand.

This returns a Food object that you are calling "apple".
apple = Food(True, 'fruit')
The Food class knows nothing about "apple". Food knows how to make Food. It has no way of knowing what you do with Food objects you create.

You could change the class to maintain a list of Food objects it created, but it has no way of knowing which of those is apple. Something like this:
class Food:
    instances = []

    def __init__(self, healthy=bool, type=str):
        self.healthy = healthy
        self.type = type
        self.instances.append(self)
Now when you create Food, the new food object is appended to Food.instances. You could print(Food.instances) to see all the Food objects that have ever been created. However, you still cannot see which of those items is the one that apple references.

Could you please describe what you are trying to accomplish. Your code snippets are not doing a good job at providing context for your question.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020