I'm new to python. I've heard that everything is an object when it comes to python even if class or function.
As far as I know, the class object is created when the program starts. So I wonder if there's some function for initializing class variables or doing something.
init function can't do because its parameter is self which's for an instance of the class. I want to access the class itself.
class Example():
def __init__(self):
# I know that this function is called when an instance of this class is created
pass
def __something__(cls):
# Is there some function for initializing class object?
# What I wanna do is I want to initialize class variables or call some functions...
# But __init__ function can't do because its parameter is self.
pass
In Python the class object is created at run time as Python is a Dynamic Language.
So if you want to initiate class variables you could just set them right after class definition
class Cls:
cls_var = "before"
print(Cls.cls_var)
Cls.cls_var = "after"
print(Cls.cls_var)
this would print "before" and "after"
you can operate the class you defined directly.
for example, your class name is Example, you can use buildin method dir to see the class method (dir(Example)), use type to see the class type (type(Example)), __dict__ see the class attributes(Example.__dict__) ...
Related
class a_class():
a_class_variable = 1
#classmethod
def a_class_method(cls):
print(a_class.a_class_variable)
a_variable = a_class()
a_variable.a_class_method()
I was just looking up calling a variable of a class inside a method within that class and I found it but, why is it that you need to name the class that the method is within when the method is in the same class?
Shouldn't the variable be visible to the method without doing so as the method is within the same class as the variable?
I can see this as being needed if you're calling a variable in a different class. For example b_class().
Is there some Pythonic reason for this convention?
I am quite new to python, so pardon me for basic question. I tried google for past few days but could not make it in my program.
Can anyone show me a good example how can I use method from One class to another in python and what is significance of __init__ while defining class.
I am using python2.7
Thanks in anticipation.
To use a method defined in one class inside of another class, you have several options:
Create an instance of B from within one of A's methods, then call B's method:
class A:
def methodInA():
b = B()
b.methodInB()
If appropriate, use the concept of inheritance (one of the defining concepts of object-oriented design) to create a subclass of the original class whose method(s) you wish to use:
class B(A):
...
__init__() is a class initializer. Whenever you instantiate an object you are invoking __init__() whether or not it is explicitly defined. It's main purpose is to initialize class data members:
class C:
def __init__(self, name):
self.name = name
def printName(self):
print self.name
c = C("George")
c.printName() # outputs George
With __init__() defined, in particular with the additional argument name in this example, you are able to differentiate between would-be generically constructed instances by allowing for different initial states from instance to instance.
There are 2 issues here:
First: Using method of class A in class B, both classes in different files
class A:
def methodOfA(self):
print "method Of A"
let the above class be in file a.py Now the class B is supposed to be in b.py. Both a.py and b.py are assumed to be on the same level or in the same location. Then b.py would look like:
import a
class B:
def methodOfB(self):
print "Method of B"
a.A().methodOfA()
You can also do this by inherting A in B
import a
class B(a.A):
def methodOfB(self):
print "Method of B"
self.methodOfA()
there are several other ways to use A in B. I will leave it to you to explore.
Now to your second question. The use of __init__ in a class. __init__ is not a constructor, as popularly believed and explained above. It is, as the name suggests, an initialization function. It is called only after the object has already been constructed and it is implicitly passed the object instance as the first argument, as signified by self in its argument list.
The actual constructor in python is called __new__, which does not need a object to call it. This is actually a specialized Static method, which receives the class instance as the first argument. __new__ is exposed for overwriting only if the class inherits form the object base class of python
Whatever other arguments are passed while creating an object of a class, first go to __new__ and then are passed with the object instance to the __init__, if it accepts them.
The init function is what is called a constructor function. When you create an instance of a class object = myClass(), init is the function that is automatically called. i.e.
That being said, to call a function from one class to another, you need to call an instance of the second class inside the first one, or vice versa. for eg.
class One():
def func(self):
#does sometthing here
class Two():
def __init__(self):
self.anotherClass = One()
#Now you can access the functions of the first class by using anotherClass followed by dot operator
self.anotherClass.func()
#When you call the main class. This is the time the __init__ function is automatically called
mainClass = Two()
Another way to access from another class is the use of oop concept called Inheritance.
class One():
def __init__(self):
print('Class One Called')
def func(self):
print('func1 Called')
class Two(One):
def __init__(self):
One.__init__(self,) #This basically creates One's instance
print('Main Called')
c= Two()
c.func()
The output for this is:
Class One Called
Main Called
func1 Called
I am trying to call the methods in CSVDatasource in my testing class by typing this code from ETL.CSVDatasource import CSVDatasource and to call the necessary methods but I have been receiving errors like TypeError: unbound method preprocess_col() must be called with CSVDatasource instance as first argument (got DataFrame instance instead)
http://imgur.com/8sfygtA -> Image of my coding path
Anyone can guide me on calling out the method in the other class so that I can call the method and do testing in my testing classs?
Thanks.
Generally, an instance of the class has to be created before calling the method of the class. For example,
class Person:
def __init__(self,name):
self.name=name
def who(self):
print 'I am {}'.format(self.name)
#staticmethod
def species():
print 'I am human.'
If we want to call the method who inside the class Person, we have to create an instance of class as follows:
if __name__=='__main__':
p1=Person('Qing Yong')
p1.who() #I am Qing Yong
However, if a method doesn't require self but you want to put it inside the class as this method may strongly related to you class in some senses. You may declare it as static method by using the decorator #staticmethod, like the method species
This static method can be called either through instance or through class directly as follows.
if __name__=='__main__':
p1.species() #I am human.
Person.species() #I am human.
Depending on the context of your code, you may choose either way to use the method inside your class.
I'm trying to modify class attribute by reference to object in __init__ method and then use it in another method. Sadly the following code sample doesn't work as expected...
CODE
class Translator:
#list of attributes
parser=None
def __init__(self):
parser = Parser_class() ...
#some other commands
def Translate(self):
something=self.parser.GenerateHead() ...
#more commands
COMPILE ERR
AttributeError: 'NoneType' object has no attribute 'GenerateHead'
I know that I can give it to the Translate method as argument, I'm just curious why this statement within Python doesn't work.
You're doing your instance attributes wrong.
First off, you don't need to declare your attributes ahead of time. Putting parser = None at the top level of the class creates a class variable named parser, which I don't think is what you want. Usually in Python you can add new instance attributes at any time by a simple assignment: instance.attr = "whatever".
Second, when you want to do an instance assignment from within a method, you need to use self to refer to the instance. If you leave off self, you'll be assigning to a local variable inside your function, not to an instance or class variable. Actually, the specific name self isn't necessary, but you do need to use the first argument to the method (and it's probably not a good idea to break the convention of naming that self).
So, to fix your code, do this:
class Translator:
# don't declare variables at class level (unless you actually want class variables)
def __init__(self):
self.parser = Parser_class() # use self to assign an instance attribute
def Translate(self):
something = self.parser.GenerateHead() # this should now work
This simple example is what I dont get to work or understand in my more complex script:
class printclass():
string="yes"
def dotheprint(self):
print self.string
dotheprint(self)
printclass()
When the class is called, I expected it to run the function, but instead it will tell me that "self is not defined". Im aware this happens on the line:
dotheprint(self)
But I dont understand why. What should I change for the class to run the function with the data it already has within? (string)
You misunderstand how classes work. You put your call inside the class definition body; there is no instance at that time, there is no self.
Call the method on the instance:
instance = printclass()
instance.dotheprint()
Now the dotheprint() method is bound, there is an instance for self to refer to.
If you need dotheprint() to be called when you create an instance, give the class an __init__ method. This method (the initializer) is called whenever you create an instance:
class printclass():
string="yes"
def __init__(self):
self.dotheprint()
def dotheprint(self):
print self.string
printclass()
You really need to understand Object-Oriented Programming and its implementation in Python.
You cannot "call" a class like any function. You have to create an instance, which has a lifetime and methods linked to it :
o = printclass() # new object printclass
o.dotheprint() #
A better implementation of your class
class printclass():
string="yes" #beware, this is instance-independant (except if modified later on)
def dotheprint(self):
print self.string
def __init__(self): # it's an initializer, a method called right after the constructor
self.dotheprint()