Python Forum
How to access class variable? instances vs class
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to access class variable? instances vs class
#1
Hello everyone, I am learning OOP in python, specifically class variables. It is clear to me what they are, but I do not get why they should be accessed through the instance. Referring to the following tutorial in the method apply_raise the variable can be accessed through the instance (line 15 --> self.pay = int( self.pay * self.raise_amount )). I tried to access the variable through the class (line 16 --> self.pay = int( self.pay * Employee.raise_amount ), and it works in the same way, at least it looks so to me. Is there any difference?

class Employee:

    raise_amount = 1.04

    def __init__(self ,first ,last ,pay ):
        self.first = first
        self.last = last
        self.pay = pay
        self.email = first+"."+last+"@company.com"

    def fullname(self):
        return "{} {}".format(self.first, self.last)

    def apply_raise(self):
        self.pay = int( self.pay * self.raise_amount )
       #self.pay = int( self.pay * Employee.raise_amount )
        return self.pay 
Reply


Messages In This Thread
How to access class variable? instances vs class - by drSlump - Dec-10-2019, 03:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How does this code create a class? Pedroski55 6 479 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  class definition and problem with a method HerrAyas 2 290 Apr-01-2024, 03:34 PM
Last Post: HerrAyas
  Printing out incidence values for Class Object SquderDragon 3 319 Apr-01-2024, 07:52 AM
Last Post: SquderDragon
  class and runtime akbarza 4 421 Mar-16-2024, 01:32 PM
Last Post: deanhystad
  Operation result class SirDonkey 6 582 Feb-25-2024, 10:53 AM
Last Post: Gribouillis
  The function of double underscore back and front in a class function name? Pedroski55 9 738 Feb-19-2024, 03:51 PM
Last Post: deanhystad
  super() and order of running method in class inheritance akbarza 7 816 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Class test : good way to split methods into several files paul18fr 4 511 Jan-30-2024, 11:46 AM
Last Post: Pedroski55
  Good class design - with a Snake game as an example bear 1 1,860 Jan-24-2024, 08:36 AM
Last Post: annakenna
  question about __repr__ in a class akbarza 4 641 Jan-12-2024, 11:22 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020