1

(I'm very new to both python and stackoverflow.)

def A():
    def B():
        print("I'm B")
    A.B = B

A()
A.B()

output:

"I'm B"

This works well. What I want is to put that in a class like this(doesn't work. I just tried..)

class Student:
    def A(self):
        def B():
            print("I'm B")
        self.A.B = B

I have no Idea how to make the class and how to call the sub function in the class.

cavalist
  • 85
  • 2
  • 8

3 Answers3

1

You don't need to reference self because the inner function B is defined there. It should be like this:

class Student:
    def A(self):
        def B():
            print("I'm B")
        B()
Josep Anguera
  • 101
  • 2
  • 4
1

Python functions are first-class objects. What is first class function in Python

So the first piece of code is perfectly valid. It just adds a property B to the function, which can later be called using A.B().

But for the second piece of code, this is invalid, as self.A returns a reference to A method of class Student

<bound method Student.A of <__main__.Student object at 0x7f5335d80828>>

self.A does not have an attribute B, so it returns an error

AttributeError: 'method' object has no attribute 'B'

Now a quick fix would be to assign it to self.B

class Student:
    def A(self):
        def B():
            print("I'm B")
        self.B = B

a = Student()
a.A()
a.B()

Although the above code works, it is a very bad way, as you will have to always call A for every object instantiated before calling B.

Raj
  • 664
  • 4
  • 16
  • According to my understanding, function can have property, and method can't have attribute. Is this correct? – cavalist Dec 14 '19 at 13:38
-2

I never use classes, but could you do it this way?

class A:                       
    def __call__(self):          //  so you can call it like a function
        def B():               
            print("i am B")     
        B()

call_A = A()                     //  make the class callable
call_A()                         //  call it