-7

How using one self instence in few subclasses have some code like this:

class User(object):

     def __init__(self)
         self.user_session = Session()

     def wallet_sum(self):
         self.user_session.get('current wallet sum')

     class Action(object):

         def __init__(self):
             self.user_session = User.user_session 

         def buy_dog(self):
             self.user_session.post('buy_dog')

     class Listing(object)

         def my_dogs(self):
             self.user_session.get('all_my_dogs')

user = User()

user.Action.buy_dog()

user.Listing.my_dogs()

i want to create one User object with one self and do some actions with it

i try:

user.Action().my_dogs()
AttributeError: type object 'User' has no attribute 'user_session '


user.Action.my_dogs()
TypeError: Action() missing 1 required positional argument: 'self'

2 Answers2

3

You only defined classes inside the namespace of class User. An instance of User don't have magically instances of the inner classes (i.e. in Python there is nothing like a inner class). So class definitions inside other classes in normally not useful.

You have to give the other classes an explicit reference to your user object:

class User(object):
     def __init__(self)
         self.user_session = Session()
         self.action = Action(self)
         self.listing = Listing(self)

     def wallet_sum(self):
         self.user_session.get('current wallet sum')

 class Action(object):
     def __init__(self, user):
         self.user_session = user.user_session 

     def buy_dog(self):
         self.user_session.post('buy_dog')

 class Listing(object)
     def __init__(self, user):
         self.user = user

     def my_dogs(self):
         self.user.user_session.get('all_my_dogs')

user = User()
user.action.buy_dog()
user.listing.my_dogs()
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Great answer, Daniel. For anyone curious, here's an example of where a nested/inner class might be useful: http://stackoverflow.com/a/78858/1759987 – Aaron Apr 11 '16 at 18:23
0

AttributeError: type object 'User' has no attribute 'user_session'. You are getting this from self.user_session = User.user_session. User has no attribute called user_session. Rather an instance User() has.

Anyway, inner classes?? See what happens if you just write a random print statement or a def inside a class definition. It is perfectly legal and pointless (in general). Either

  1. Convert them to methods
  2. Write separate classes and compose them into a new class.
C Panda
  • 3,297
  • 2
  • 11
  • 11