Python Forum

Full Version: Class question
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello i have been learning Python 3 and its going in quite well.

But i have a query about classes.

i have the below code

class Student(object):
    def __init__(self, name="Rob", grade='A', county="Essex"):
        self.name = name
        self.grade = grade
        self.county = county

    student1 = Student()
    print(student1.name)
when i run in pycharm, i get the following error

Error:
student1 = Student() NameError: name 'Student' is not defined
can someone point out what im doing wrong please.

Kind Regards

Rob
You need to either put student1 = Student() in the function or take it out of the class. You have it aligned with your function.
You have referred to the class inside the class definition. Modify your indents to do it outside.

class Student(object):
    def __init__(self, name="Rob", grade='A', county="Essex"):
        self.name = name
        self.grade = grade
        self.county = county

student1 = Student()
print(student1.name)
Output:
Rob
Check your indentation @robdineen - the last two lines are inside the function
(May-28-2020, 09:27 PM)bowlofred Wrote: [ -> ]You have referred to the class inside the class definition. Modify your indents to do it outside.

class Student(object):
    def __init__(self, name="Rob", grade='A', county="Essex"):
        self.name = name
        self.grade = grade
        self.county = county

student1 = Student()
print(student1.name)
Output:
Rob

Thank you very much, stupid error, so thank you for answering.
Another one if this is even helpful

class Student(object):
    def __init__(self, name, grade, county):
        self.name = name
        self.grade = grade
        self.county = county

    def getName(self):
        return self.name

    def getGrade(self):
        return self.grade

    def getCountry(self):
        return self.county

    def __str__(self):
        return 'Name: '+ self.name + '\ngrade: ' + self.grade + '\ncountry: ' + self.county


def main():
    student1 = Student('Rob', 'A', 'Essex')
    print(student1)

if __name__ == '__main__':
    main()
Output
Name: Rob
grade: A
country: Essex
@Calli:
OP question was ansered already.
What you suggest - using getters/setters for properties is anti-pattern in python. Even in your code you don't use them in __str__() method :-)
some reading: Why don't you want getters and setters?
Just learning as much as i can thank you so much @buran i will do more reading on your link.