此代码python类和对象有什么问题

问题描述 投票:1回答:1

我有一个问题,如果我在pycharm中键入3个或更多字符,它会严重滞后。我卸载了该应用程序,并将尝试安装以查看是否可以解决问题+我正在编写一些代码。有人可以复制我的代码并将其粘贴到他的pycharm上看是否有效。如果没有,有人可以告诉我问题是什么。可能是我刚接触python的问题我的代码:

我发布时缩进有问题,所以请在运行前更正它

班级银行帐户:

def __init__(self, account_number,name,opening_balance,type_of_account):


    self.account_number = account_number

    self.name = name

    self.opening_balance = opening_balance

    self.type_of_account = type_of_account

amount_of_money = opening_balance

def __str__(self):

    print('account number: ', account_number)

    print('name: ',name)

    print("opening balance: ", opening balance)

    print('type of account: ',type_of_account)

def deposit(amount):

    global amount_of_money

    amount_of_money += amount

def withdraw(amount):

    global amount_of_money

    amount_of_money -=amount

def get_balance():

    global amount_of_money

    return str(amount_of_money) + '$'

acc1 = bank_account('66666666666666','mike',1000,'deposit')

acc1.deposit(250)

acc1.get_balance()

print(acc1)

谢谢

pycharm
1个回答
1
投票

至少可以说您的代码不好。 PyCharm在运行前应告诉您是否有任何问题。我不确定您是否正在使用滞后的马铃薯。

这里是我发现的错误:

  • opening balance应该为opening_balance

  • 缩进错误

  • 所有类函数都应将self作为第一个参数

  • 请勿使用global访问类变量。使用self.

  • PEP-8违规,可以通过按键盘上的CTRL+ALT+L进行纠正

  • __str__不应打印。它应该返回str

  • 编辑:类应遵循CamelCaps约定

  • 这不是错误,但我建议坚持使用单引号或双引号来封装字符串。每个人至少应该与自己保持一致。

可能存在一些逻辑错误,但这取决于您要对类进行的操作。

class BankAccount:
    def __init__(self, account_number, name, opening_balance, type_of_account):
        self.account_number = account_number

        self.name = name

        self.opening_balance = opening_balance

        self.type_of_account = type_of_account

        self.amount_of_money = opening_balance

    def __str__(self):
        result = "account number: " + str(self.account_number)
        result += "\nname: " + str(self.name)
        result += "\nopening balance: " + str(self.opening_balance)
        result += "\ncurrent balance: " + str(self.amount_of_money)
        result += "\ntype of account: " + str(self.type_of_account)
        return result

    def deposit(self, amount):
        self.amount_of_money += amount

    def withdraw(self, amount):
        self.amount_of_money -= amount

    def get_balance(self):
        return str(self.amount_of_money) + "$"


acc1 = BankAccount("66666666666666", "mike", 1000, "deposit")

acc1.deposit(250)

print(acc1.get_balance())

print(acc1)

我强烈建议您遵循有关Python的系列教程。数小时不知所措,您将不会大惊小怪。对我来说,Corey Schafer的This one似乎非常专业,我从他的其中一部教程中学到了Flask。

如果PyCharm对您的计算机来说负担太重,那么还有许多其他更轻便的编辑器,例如Atom或Sublime Text。

© www.soinside.com 2019 - 2024. All rights reserved.