S
S
Snowdevil2021-06-16 20:48:58
Python
Snowdevil, 2021-06-16 20:48:58

NameError: name 'money' is not defined. Where is the mistake?

sender(id, 'Баланс\n\nНаличные: {}\nАлмазы: {}'.format(money, ruby), balance)
NameError: name 'money' is not defined

class User():
  def __init__(self, id, money, ruby, ruderalis, vip):
    self.id = id
    self.money = money
    self.ruby = ruby
    self.ruderalis = ruderalis
    self.vip = vip

def save_bd(users):
  lines = []
  for user in users:
    lines.append(f'"id" : {user.id}, "money" : {user.money}, "ruby" : {user.ruby}, "ruderalis" : {user.ruderalis}, "vip" : {user.vip}')
  lines = '\n'.join(lines)
  with open(f'{tdir(__file__)}/data.txt'.replace('\\', '/').replace('main.py/', ''), 'w', encoding = 'utf-8') as file:
    file.write(lines)
    file.close()

def read_bd():
  users = []
  with open(f'{tdir(__file__)}/data.txt'.replace('\\', '/').replace('main.py/', ''), 'r', encoding = 'utf-8') as file:
    lines = [x.replace('\n', '') for x in file.readlines()]
    file.close()
  for line in lines:
    line = eval('{' + line + '}')
    if line != '{}':
      users.append(User(id = line['id'], money = line['money'], ruby = line['ruby'], ruderalis = line['ruderalis'], vip = line['vip']))
  return users

users = read_bd()

for event in longpoll.listen():
  if event.type == VkEventType.MESSAGE_NEW:
    if event.to_me:

      id = event.user_id
      msg = event.text.lower()

      elif msg.find('баланс') != -1:
        sender(id, f'Баланс\n\nНаличные: {money}\nАлмазы: {ruby}', balance)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Matvey Polubryukhov, 2021-07-06
@matveypol003

Good day!
The NameError occurs because the money variable is indeed undefined. As far as I understand, in your main loop:

for event in longpoll.listen():
    ...

the users variable is not used, there is no creation of an object of the User class anywhere. And the money variable is defined in this class. From the class, it can be called via
self.money
A from outside:
user.money
This is only if the user variable is defined, i.e. there is a line
user = User(...)
This is logical, because you don't have an instance of the class, you can't access what's inside.
Hence the NameError.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question