Hi,
I don't know the difference between class variables and instance variables. Can anybody give me an example?
Thank you so much:)
Here you have an example of a class name Animal and some instance names (dog, cat, cow) ...
class Animal:
"""
class names by convention are capitalized
"""
# category is global to the class and is available to all
# instances of class Animal
category = "animal"
def __init__(self, animal, sound):
"""
__init__() is the 'constructor' of the class instance
when you create an instance of Animal you have to supply
it with the name and the sound of the animal
'self' refers to the instance
if the instance is dog, then
name and sound will be that of the dog
'self' also makes name and sound available
to all the methods within the class
"""
self.name = animal
self.sound = sound
def speak(self):
"""
the first argument of a class method is always self
this method needs to be called with self.speak() within
the class, or the instance_name.speak() outside the class
"""
print( "The %s goes %s" % (self.name, self.sound) )
# create a few class instances
# remember to supply the name and the sound for each animal
dog = Animal("dog", "woof")
cat = Animal("cat", "meeouw")
cow = Animal("cow", "mooh")
# testing ...
# now you can call each animals function/method speak()
# by simply connecting instance_name and speak() with a '.'
cow.speak()
cat.speak()
dog.speak()
# you can also access variables associated with the instance
# since cow is the instance
# self.sound becomes cow.sound
print(cow.sound)
# category is a class variable common to all istances
print(dog.category)
print(cat.category)
print(cow.category)
"""my result -->
The cow goes mooh
The cat goes meeouw
The dog goes woof
mooh
animal
animal
animal
"""
According to advice from The_Kernel (thanks)
category" is considered a class variable,
self.name and self.sound are instance variables.
A class variable is shared across instances of the class, while an instance variable is unique to that instance of the class. Consider the following example:
class Foo:
name = "FOO"
def __init__(self, value):
self.value = value
mine = Foo("bar")
mine_2 = Foo("taz")
print mine.value, mine.name
print mine_2.value, mine.name
Foo.name = "BAR"
print mine.value, mine.name
print mine_2.value, mine.name
#output is:
# bar FOO
# taz FOO
# bar BAR
# taz BAR
thx guys i understood
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.