-3

I am learning python3 and I want to know that how I can

class testit:
    def assigna():
        a = "Hi"

    def geta(self):
        print(self.a)


test = testit
print(test.geta())

How can I access a inside of geta as suggested in comments I tried to use self.a and it gives me an error.

Here is my Updated Code

class testit:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        print(self.a)


test = testit
print(test.geta())

and here is the error.

Traceback (most recent call last):
  File "test.py", line 44, in <module>
    print(test.geta())
TypeError: geta() missing 1 required positional argument: 'self'

quamrana
  • 37,849
  • 12
  • 53
  • 71
For This
  • 153
  • 1
  • 2
  • 8
  • Did you mean: `self.a = "Hi"`? – quamrana May 30 '20 at 14:21
  • You also would need to create an *instance* of the `testit` class and *call* its method `test.assigna()`, and add a parameter (by convention called `self`) to `assigna`. – mkrieger1 May 30 '20 at 14:21
  • When i try to do this it gives me an error TypeError: geta() missing 1 required positional argument: 'self' now here is how my code looking loke – For This May 30 '20 at 14:31
  • Please update your question with the full error traceback. – quamrana May 30 '20 at 14:31
  • 1
    @ForThis Read up on [Tutorial - 9.3.5. Class and Instance Variables](https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables) – stovfl May 30 '20 at 14:54

2 Answers2

2

when you pass self in argument of method it refers to an object so you have to assign a as object attribute before.

you also have to make an instance of this class with calling it like this classname().

class TestIt:
    def assigna(self):
        self.a = "Hi"

    def geta(self):
        return self.a


test = TestIt()
test.assigna()
test.geta()
print(test.geta())
NoSkillMan
  • 136
  • 6
1

You can access the instance based variable through self but you have to assign to it in the constructor, Here is a little code for you:

class Test:
  def __init__(self):
      self.a = ""
  def assign_a(self):
      self.a = "Hi"
  def get_a(self):
     print(self.a)

So you can access it like :

test = Test()
test.assign_a()
test.get_a()

Here look at the __init__ function carefully it is called the constructor and inside it we are declaring variable a through self. Now this variable will be accessible throughout the class.

Enjoy learning !!

quamrana
  • 37,849
  • 12
  • 53
  • 71
Kartikeya Sharma
  • 553
  • 1
  • 5
  • 22