I understand in Python a class can have a class variable (shared among all objects), and also a unique object variable (which is uniquely assignable from object to object).
However, why do I get a 'object has no attribute 'nObjVar' error, when I try to access that object's variable from another function?
class TestClass:
nClassVar1 = 0 #Class Var shared across all objects
def __init__(self, defaultInitVal = 0):
nObjVar = defaultInitVal #Object Var Only
def MyFuncMult(self):
result = nObjVar * 10;
return ( result )
The reason is because you are defining it as a local variable in the init, if you want it to be a member of the object you need to type
self.nObjVar
this will set it to a member
To make a variable available to all methods in a class, save it in the self namespace.
class TestClass:
nClassVar1 = 0 #Class Var shared across all objects
def __init__(self, defaultInitVal = 0):
self.nObjVar = defaultInitVal #Object Var Only
def MyFuncMult(self):
result = self.nObjVar * 10;
return ( result )
Try self.nObjVar to reference the variable of the instance.
Related
Here is the question of a python code asked on InfyTQ mock test.
class classOne:
__var_one = 1001
def __init__(self,var_two):
self.__var_two = var_two
self.__var_five = 5
def method_one(self):
var_four = 50
self.__var_five = ClassOne.__var_one + self.__var_two + var_four
Now, I want to ask if the variable
self.__var_five of function method_one should be considered a new instance variable or not?
Because there is already a self.__var_five in __init__ function.
Also,
I learned the concept of global,local,static and instance variable from given below code.
Is it correct?
#global, local, static, instance variable.
#global variable are defined at the top of program or defined using keyword:global
global global_var1 = 0
global_var2 = 1
def local_variable:
#local variable are defined inside of a function.
local_var1 = 2
class static_instance:
#static/classs variable are defined inside of a class.
static_var1 = 3
def __init__(self):
#all variables defined in the function of a class starting with self.
self.instance_var1 = 4
def static(self):
self.instance_var2 = 5
local_var2 = 6 #local variable as it is in a function.
static_var2 = 6
It's the same instance variable (called an attribute in Python). method_one is simply updating its value.
Most of your understandings in the second code block are correct. However, when a method does:
self.static_var1 = 4
it creates an instance attribute named static_var1. This is independent of the class attribute that was declared outside the methods, which is shared among all instances that don't reassign it. But since you do the assignment in the __init__() method, all instances get their own attribute. The only way to access the static value would be with static_instance.static_var1.
This class unlike function can have initialized internal variables.
The fact that the variables are internal makes it more orderly and that it's initialized more efficiently.
import re
class clean_ship_to:
pattern_num_int = re.compile(r'[\W\_]+') # initialized internal variable
#classmethod
def clean(cls, ship_to):
ship_to['num_int'] = cls.pattern_num_int.sub('', ship_to['num_int'])[:35]
ship_to['contact_name'] = ship_to['contact_name'][:35]
ship_to['contact_phone'] = ship_to['contact_phone'][:25]
return ship_to
This is callable with clean_ship_to.clean(ship_to) and I want clean_ship_to(ship_to)
class clean_ship_to(dict):
"""
Clean dict ship_to
"""
# dict inheritance fix pylint(unsubscriptable-object) alert
pattern_num_int = re.compile(r'[\W\_]+')
def __new__(cls, ship_to):
ship_to['num_int'] = cls.pattern_num_int.sub('', ship_to['num_int'])[:35]
ship_to['contact_name'] = ship_to['contact_name'][:35]
ship_to['contact_phone'] = ship_to['contact_phone'][:25]
return ship_to
>>> clean_ship_to(ship_to)
{...}
We are facing a problem in accessing member attributes of a class when we the member attribute name is stored in another variable. For example : We have a class A, which has member attributes is var1, var2, var2, and upto var 100. From another class, we are trying to access var67, the name of attribute we want to access ( i.e. var67) is stored in a different variable x, as a string ("var67")(this x is generated from a different function). So from the value of x how can we access var67 attribute as we just can't do A.x . Please guide us any short approach other than building a method in class A to access variables in such case. Thanks!
MyClass:
variable = "blah"
def function(self):
print("This is a message inside the class.")
myobjectx = MyClass()
x="variable"
myobjectx.(getattr(MyClass(), x))
The last line will throw a syntax error
In python you have the getattr builtin function:
class A:
def __init__(self):
self.a67 = 10
x = "a67"
print(getattr(A(), x))
Here you have a live example
I am trying to assign a method's return to a variable and stuck with this error.
class MyClass():
def my_def(self):
return "Hello"
my_variable = my_def()
Here is the Java equivalent of what I want to do.
public class NewException {
public int method1(){
return 1;
}
public int variable = method1();
}
I am sure this is something simple, but I couldn't even find the right words to google this. Any help is appreciated.
Lets start with the difference between methods and functions, basically a method belongs to some object while a function does not. So for example
def myFunction():
return "F"
class MyClass:
value = 0
def myMethod(self, value):
old = self.value
self.value = value
return old
myClassInstance = MyClass()
print myClassInstance.myMethod(3)
# 0
print myClassInstance.myMethod(33)
# 3
print myFunction()
# F
Notice that the method is bound to the instance and it doesn't make sense to call the method before the instance is created. With that in mind, your error should make more sense. The method cannot be called without an instance (self). This is not the only kind of method, for example there are "static methods". Static methods are defined on the class, but they are called without an instance. For example:
class MyClass:
#staticmethod
def myStaticMethod():
return "static method"
# Consider using an instance attribute instead of a class attribute
def __init__(self):
self.instance_attribute = MyClass.myStaticMethod()
# Or if you need a class attribute it needs to go outside the class block
MyClass.class_attribute = MyClass.myStaticMethod()
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Python: Difference between class and instance attributes
I'm trying to get my head around OOP in Python and I'm a bit confused when it comes to declare variables within a class. Should I declare them inside of the __init__ procedure or outside it? What's the difference?
The following code works just fine:
# Declaring variables within __init__
class MyClass:
def __init__(self):
country = ""
city = ""
def information(self):
print "Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
But declaring the variables outside of the __init__ procedure also works:
# Declaring variables outside of __init__
class MyClass:
country = ""
city = ""
def information(self):
print "Hi! I'm from %s, (%s)"%(self.city,self.country)
me = MyClass()
me.country = "Spain"
me.city = "Barcelona"
me.information()
In your first example you are defining instance attributes. In the second, class attributes.
Class attributes are shared between all instances of that class, where as instance attributes are "owned" by that particular instance.
Difference by example
To understand the differences let's use an example.
We'll define a class with instance attributes:
class MyClassOne:
def __init__(self):
self.country = "Spain"
self.city = "Barcelona"
self.things = []
And one with class attributes:
class MyClassTwo:
country = "Spain"
city = "Barcelona"
things = []
And a function that prints out information about one of these objects:
def information(obj):
print "I'm from {0}, ({1}). I own: {2}".format(
obj.city, obj.country, ','.join(obj.things))
Let's create 2 MyClassOne objects and change one to be Milan, and give Milan "something":
foo1 = MyClassOne()
bar1 = MyClassOne()
foo1.city = "Milan"
foo1.country = "Italy"
foo1.things.append("Something")
When we call information() on the foo1 and bar1 we get the values you'd expect:
>>> information(foo1)
I'm from Milan, (Italy). I own: Something
>>> information(bar1)
I'm from Barcelona, (Spain). I own:
However, if we were to do exactly the same thing, but using instances of MyClassTwo you'll see that the class attributes are shared between instances.
foo2 = MyClassTwo()
bar2 = MyClassTwo()
foo2.city = "Milan"
foo2.country = "Italy"
foo2.things.append("Something")
And then call information()...
>>> information(foo2)
I'm from Milan, (Italy). I own: Something
>>> information(bar2)
I'm from Barcelona, (Spain). I own: Something
So as you can see - things is being shared between the instances. things is a reference to a list that each instance has access to. So if you append to things from any instance that same list will be seen by all other instances.
The reason you don't see this behaviour in the string variables is because you are actually assigning a new variable to an instance. In this case that reference is "owned" by the instance and not shared at the class level. To illustrate let's assign a new list to things for bar2:
bar2.things = []
This results in:
>>> information(foo2)
I'm from Milan, (Italy). I own: Something
>>> information(bar2)
I'm from Barcelona, (Spain). I own:
You're two versions of the code are very different. In python, you have 2 distinct entities: classes and class instances. An instance is what is created when you do:
new_instance = my_class()
You can bind attributes to an instance within __init__ via self (self is the new instance).
class MyClass(object):
def __init__(self):
self.country = "" #every instance will have a `country` attribute initialized to ""
There's nothing terribly special about self and __init__. self is the customary name that is used to represent the instance that gets passed to every method (by default).
a.method() #-> Inside the class where `method` is defined, `a` gets passed in as `self`
The only thing special here is that __init__ gets called when the class is constructed:
a = MyClass() #implicitly calls `__init__`
You can also bind attributes to the class (putting it outside __init__):
class MyClass(object):
country = "" #This attribute is a class attribute.
At any point, you can bind a new attribute to an instance simply by:
my_instance = MyClass()
my_instance.attribute = something
Or a new attribute to a class via:
MyClass.attribute = something
Now it gets interesting. If an instance doesn't have a requested attribute, then python looks at the class for the attribute and returns it (if it is there). So, class attributes are a way for all instances of a class to share a piece of data.
Consider:
def MyClass(object):
cls_attr = []
def __init__(self):
self.inst_attr = []
a = MyClass()
a.inst_attr.append('a added this')
a.cls_attr.append('a added this to class')
b = MyClass()
print (b.inst_attr) # [] <- empty list, changes to `a` don't affect this.
print (b.cls_attr) # ['a added this to class'] <- Stuff added by `a`!
print (a.inst_attr) #['a added this']
When you define a variable in class scope (outside any method), it becomes a class attribute. When you define a value in method scope, it becomes a method local variable. If you assign a value to an attribute of self (or any other label referencing an object), it becomes (or modifies) an instance attribute.