After going through some lectures on class and objects, what I have understood is that if a function is a part of a class then it can be accessed by object which is known as method and if a function is outside a class, then it can be accessed directly.
So for example -
1)
def introduce():
return 'My name is Joseph'
student1 = introduce()
Here since introduce is not within any class , we directly used introduce function and the result shall be 'My name is Joseph' which shall be stored in student1
2)
class room():
def introduce(self):
return 'My name is Joseph'
student1 = introduce()
a = student1.introduce()
Here this introduce function is inside room class and therefore to use it we have to associate a object with a class and then use it
Now going by this lets take an example of Pandas
we have a function named as - pandas.read()
I think pandas is a class but then here does it mean that pandas is a object and a read() is a function inside pandas ? Am I missing something ?
Shouldn't this be the case ?
df = pandas() # making an object of pandas class
df.read() # then accessing the read function inside pandas class
Kindly assist me
There are 3 types of functions(methods) you can have inside an python class.
Instance Method
Class Method
Static Method
Here's a thing to see that what you have created the method named introduce inside room that is "Instance Method". Which takes object as self parameter meaning which can be accessed by Instance(object).
You can also define a Class Method in following way.
class room():
#classmethod
def introduce(self):
return 'My name is Joseph'
This can be accessed as
room.introduce()
If you want to know about more about what is static or class methods. Visit here Check out
Note: The website has no connection to me I just found this online and I liked it so shared it ;)
Related
I am new in Python before I have only Java experience , In python I need to invoked parameter constructor while I have many class and class name identifies on runtime so I need to create that class Object with constructor and as well method. with static it is working fine. for java I can use class.forName(class_name). I tried with importlib, string to class but did not work.
Excample:
class A
def _init_(self,name):
self.name = name
def some_method(self):
print('method print',self.name)
Expectation: want to achieve-
instance = A('instance A')
instance.some_method()
in the above code class A will be identified on Run time and similar many class we have and above code I need to implement dynamically, how can achieve this.
If classes are in another file, use getattr
import module_with_my_classes
x = getattr(module_with_my_classes, 'A')
If you are in the file as the class definitions, use globals
x = globals()['A']
# x is a A instance
How To create a methods which are common to a particular object just like creating instance attrbitue obj.instance_attribute
A method which belongs specifically for a single object ?
The link contains the code. I need to create method only for this object and not all instance of class.
Creating class methods and attribute. The instance attrbitue. How to create instance methods
class A():
def init(self):
self.class_variable = 999999
def class_methods(self):
#available to all object
print("Hey")
obj = A()
obj.class_variable
999999
obj.class_methods()
Hey
obj.instance_attribute = 40404040 #common to particular object
obj.instance_attribute
40404040
#a method which is common to only this object
obj.new_method():
SyntaxError: invalid syntax
obj.new_mehtod(self):
SyntaxError: invalid syntax
I think you are mixing up terminology. Every "normal" method is a instance method - that means it applies the function without affecting any other instances of this class. To reference the instance, use the passed self keyword.
Defining a method for a single instance inside the generator/ class definition does not make sense in an OOP-context. If you create a car class, every instance of this class should be able to access its methods, like drive().
The only way to add a unique function is to add it after instantiating the object. This can be done with the types.MethodType method, which binds the function to the class instance:
from types import MethodType
def fly(self):
print(f"i, {self.name}, can fly")
class Car:
def __init__(self, name):
self.name = name
car_1 = Car("car one")
car_2 = Car("car two")
car_1.fly = MethodType(fly, car_1)
car_1.fly() # i, car one, can fly
car_2.fly() # AttributeError: 'Car' object has no attribute 'fly'
As you can see, car_1 has the class fly, which references car_1's name, while car_2 does not have this function.
But you should seriously reconsider what you are trying to achieve here.
I am learning python and doing an exercise about classes. It tells me to add an attribute to my class and a method to my class. I always thought these were the same thing until I read the exercise. What is the difference between the two?
Terminology
Mental model:
A variable stored in an instance or class is called an attribute.
A function stored in an instance or class is called a method.
According to Python's glossary:
attribute: A value associated with an object which is referenced by
name using dotted expressions. For example, if an object o has an
attribute a it would be referenced as o.a
method: A function which is defined inside a class body. If called as an attribute of an instance of that class, the method will get the instance object as its first argument (which is usually called self). See function and nested scope.
Examples
Terminology applied to actual code:
a = 10 # variable
def f(b): # function
return b ** 2
class C:
c = 20 # class attribute
def __init__(self, d): # "dunder" method
self.d = d # instance attribute
def show(self): # method
print(self.c, self.d)
e = C(30)
e.g = 40 # another instance attribute
A method is an attribute, but not all attributes are methods. For example, if we have the class
class MyClass(object):
class_name = 'My Class'
def my_method(self):
print('Hello World!')
This class has two attributes, class_name and my_method. But only my_method is a method. Methods are functions that belong to your object. There are additional hidden attributes present on all classes, but this is what your exercise is likely talking about.
A quick,simplified explanation.
Attribute == characteristics.
Method == operations/ actions.
For example, Let's describe a cat (meow!).
What are the attributes(characteristics) of a cat?
It has different breed, name, color, whether they have spots...etc.
What are methods (actions) of a cat?
It can meow, climb, scratch you, destroy your laptop, etc.
Notice the difference, attributes define characteristics of the cat.
Methods, on the other hand, defines action/operation (verb).
Now, putting the above definition in mind, let's create an object of class 'cat'...meowww
class Cat():
To create attributes, use def init(self, arg1, arg2) - (as shown below).
The 'self' keyword is a reference to a particular instance of a class.
def __init__(self, mybreed, name):
# Attributes
self.breed = mybreed
self.name = name
# Operations/actions --> methods
def kill_mouse(self):
print('Insert some method to kill mouse here')
Notice (above) 'mybreed' is an input argument that the user need to specify, whereas self.breed is an attribute of the instance assigned to 'mybreed' argument. Usually, they're the same (e.g. breed for both, self.breed = breed). Here, it's coded differently to avoid confusion.
And attributes are usually written as 'self.attribute_name' (as shown above).
Now, methods are more like actions, or operations, where you define a function inside the body of a class to perform some operation, for example, killing a mouse. A method could also utilize the attributes that you defined within the object itself.
Another key difference between a method and attribute is how you call it.
For example, let's say we create an instance using the above class we defined.
my_cat = Cat()
To call an attribute, you use
my_cat.name
or
my_cat.breed
For methods, you call it to execute some action. In Python, you call method with an open and close parenthesis, as shown below:
my_cat.kill_mouse()
A method is a function defined in the class. An attribute is an instance variable defined in the class.
Example:
class Example(object):
def __init__(self, name):
self.name = name
def hello(self):
print 'Hi, I am ' + self.name
Here hello is a method, and name is an attribute.
class example:
global a
# a=0
def __init__(self,x,y):
self.fname=x
self.lname=y
def show(self):
return "first name: {} & Last name: {}".format(self.fname,self.lname)
obj1=example('reyan','ishtiaq')
obj2=example('ishtiaq','reyan')
print('method associated with obj1: '+ obj1.show())
print('method associated with obj2: '+ obj2.show())
obj1.a=20
obj2.a=30
print(obj1.a)
print(obj2.a)
output:
method associated with obj1: first name: reyan & Last name: ishtiaq................
method associated with obj2: first name: ishtiaq & Last name: reyan................
20
30
#Below u can see that I made a class called "example" with two class attributes:
variable1 and variable2.
class example():
def init(self, variable1, variable2):
self.variable1 = variable1
self.variable2 = variable1
i did not construct a method inside this class. Notice that variable1 comes first and after comes variable2 inside the init():
#below i created an object "object1" with the example class. I created the example class with two arguments "variable1" and "variable2". "self" does not count), so i have to pass two arguments when calling the example class. I gave two variables "10" and "20".
object1 = example(10,20)
with the code below i just get the value of the first argument, which is 10.
print(object1.variable1)
Look at this code:
class MyClass():
# Why does this give me "NameError: name 'self' is not defined":
mySelf = self
# But this does not?
def myFunction(self):
mySelf2 = self
Basically I want a way for a class to refer to itself without needing to name itself specifically, hence I want self to work for the class, not just methods/functions. How can I achieve this?
EDIT: The point of this is that I'm trying to refer to the class name from inside the class itself with something like self.class._name_ so that the class name isn't hardcoded anywhere in the class's code, and thus it's easier to re-use the code.
EDIT 2: From what I've learned from the answers below, what I'm trying to do is impossible. I'll have to find a different way. Mission abandoned.
EDIT 3: Here is specifically what I'm trying to do:
class simpleObject(object):
def __init__(self, request):
self.request = request
#view_defaults(renderer='string')
class Test(simpleObject):
# this line throws an error because of self
myClassName = self.__class__.__name__
#view_config(route_name=myClassName)
def activateTheView(self):
db = self.request.db
foo = 'bar'
return foo
Note that self is not defined at the time when you want the class to refer to itself for the assignment to work. This is because (in addition to being named arbitrarily), self refers to instances and not classes. At the time that the suspect line of code attempts to run, there is as of yet no class for it to refer to. Not that it would refer to the class if there was.
In a method, you can always use type(self). That will get the subclass of MyClass that created the current instance. If you want to hard-code to MyClass, that name will be available in the global scope of the methods. This will allow you to do everything that your example would allow if it actually worked. E.g, you can just do MyClass.some_attribute inside your methods.
You probably want to modify the class attributes after class creation. This can be done with decorators or on an ad-hoc basis. Metaclasses may be a better fit. Without knowing what you actually want to do though, it's impossible to say.
UPDATE:
Here's some code to do what you want. It uses a metaclass AutoViewConfigMeta and a new decorator to mark the methods that you want view_config applied to. I spoofed the view_config decorator. It prints out the class name when it's called though to prove that it has access to it. The metaclass __new__ just loops through the class dictionary and looks for methods that were marked by the auto_view_config decorator. It cleans off the mark and applies the view_config decorator with the appropriate class name.
Here's the code.
# This just spoofs the view_config decorator.
def view_config(route=''):
def dec(f):
def wrapper(*args, **kwargs):
print "route={0}".format(route)
return f(*args, **kwargs)
return wrapper
return dec
# Apply this decorator to methods for which you want to call view_config with
# the class name. It will tag them. The metaclass will apply view_config once it
# has the class name.
def auto_view_config(f):
f.auto_view_config = True
return f
class AutoViewConfigMeta(type):
def __new__(mcls, name, bases, dict_):
#This is called during class creation. _dict is the namespace of the class and
# name is it's name. So the idea is to pull out the methods that need
# view_config applied to them and manually apply them with the class name.
# We'll recognize them because they will have the auto_view_config attribute
# set on them by the `auto_view_config` decorator. Then use type to create
# the class and return it.
for item in dict_:
if hasattr(dict_[item], 'auto_view_config'):
method = dict_[item]
del method.auto_view_config # Clean up after ourselves.
# The next line is the manual form of applying a decorator.
dict_[item] = view_config(route=name)(method)
# Call out to type to actually create the class with the modified dict.
return type.__new__(mcls, name, bases, dict_)
class simpleObject(object):
__metaclass__ = AutoViewConfigMeta
class Test(simpleObject):
#auto_view_config
def activateTheView(self):
foo = 'bar'
print foo
if __name__=='__main__':
t = Test()
t.activateTheView()
Let me know if you have any questions.
Python has an "explict is better than implicit" design philosophy.
Many languages have an implicit pointer or variable in the scope of a method that (e.g. this in C++) that refers to the object through which the method was invoked. Python does not have this. Here, all bound methods will have an extra first argument that is the object through which the method was invoked. You can call it anything you want (self is not a keyword like this in C++). The name self is convention rather than a syntactic rule.
Your method myFunction defines the variable self as a parameter so it works. There's no such variable at the class level so it's erroring out.
So much for the explanation. I'm not aware of a straightforward way for you to do what you want and I've never seen such requirement in Python. Can you detail why you want to do such a thing? Perhaps there's an assumption that you're making which can be handled in another way using Python.
self is just a name, your self in this case is a class variable and not this for the object using which it is called,
self is treated as a normal variable and it is not defined, where as the self in the function comes from the object used for calling.
you want to treat the object reference in self as a class variable which is not possible.
self isn't a keyword, it's just a convention. The methods are attributes of the class object (not the instance), but they receive the instance as their first argument. You could rename the argument to xyzzy if you wanted and it would still work the same way.
But (as should be obvious) you can't refer to a method argument outside the body of the method. Inside a class block but outside of any method, self is undefined. And the concept wouldn't even make sense -- at the time the class block is being evaluated, no instance of the class can possibly exist yet.
Because the name self is explicitly defined as part of the arguments to myFunction. The first argument to a method is the instance that the method was called on; in the class body, there isn't an "instance we're dealing with", because the class body deals with every possible instance of the class (including ones that don't necessarily exist yet) - so, there isn't a particular object that could be called self.
If you want to refer to the class itself, rather than some instance of it, this is spelled self.__class__ (or, for new-style classes in Py2 and all classes in Py3, type(self)) anywhere self exists. If you want to be able to deal with this in situations where self doesn't exist, then you may want to look at class methods which aren't associated with any particular instance, and so take the class itself in place of self. If you really need to do this in the class body (and, you probably don't), you'll just have to call it by name.
You can't refer to the class itself within the class body because the class doesn't exist at the time that the class body is executed. (If the previous sentence is confusing, reading up about metaclasses will either clear this up or make you more confused.)
Within an instance method, you can refer to the class of the instance with self.__class__, but be careful here. This will be the instance's actual class, which through the power of inheritance might not be the class in which the method was defined.
Within a class method, the class is passed in as the first argument, much like instances are the first argument to instance methods:
class MyClass(object):
#classmethod
def foo(cls):
print cls.__name__
MyClass.foo() # Should print "MyClass"
As with instance methods, the actual class might differ due to inheritance.
class OtherClass(MyClass):
pass
OtherClass.foo() # Should print "OtherClass"
If you really need to refer to MyClass within a method of MyClass, you're pretty much going to have to refer to it as MyClass unless you use magic. This sort of magic is more trouble than it is worth.
I am a newcomer to Python. I don't understand how/why the self argument is used:
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()
This code is from a Byte of Python. This code could have just as easily been written as:
def sayHi(self, name):
print 'Hello, my name is', name
p = Person('Swaroop')
p.sayHi()
...right? What is the purpose of making name a field of self?
It seems you are oversimplifying a not so simple thing.
In object-oriented programming, a Class is a Declarative Construct which gives a blueprint as to what an object (a manifestation of this blueprint) would contain (properties) and how it would behave (members).
Every manifestation of such a Class is called an Object which has a defined and specific instance. From an object via any of this behavioral attributes called member functions/methods we need somehow to refer to that instance of the object and remember individual elements within it and make a clear distinction with the other non member entities.
Consider Your example
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
Every Instance of this Person (Tom, Dick, Harry) is unique and within each instance, to refer back to itself we need some idiom like (self in Python, this ptr is C++ or this in Java).
So in the __init__ method when you need to demarcate between the name attribute of Person with the name parameter we can easily do so with self. Not only that, at any instance we can keep on referring back to this name via the self.
Making an instance of Person p=Person('Swaroop') and then invoking sayHi contrasting to calling just a function sayHi which is not a part of an object has two implications
The Function is transient, has no state, no instance and its like Saying this Guy "Hey Mr. who ever you are say 'Hello, my name is Swaroop'". It's like on every run you have to make an imbecile make aware of his name who will forget the next moment you will meet him. It's like this Guy is suffering from Anterograde_amnesia. Calling sayHi of the instance of Person named Swaroop on the other hand would mean something like a physically existing Swaroop greeting back his Name who has a persistent memory and would never forget unless he adopts a new name.
The Function never remembers but forgets every time the call ends. The Person object will remember the name until you explicitly or implicitly Kill That Person.
If you have a background of C++ and might be wondering why on earth do we need to add that extra parameter to the function call where as in C++ this pointer is never passed.
Well Candidly speaking it does. If you read the C++ calling convention, whether X86 or X64, the this pointer is passed through the register ecx to the method to give an handle to itself. This is more explicit here where we deliberately pass the handle to the current instance to the method.
Have a look at the new method sayHiTo:
class Person:
def __init__(self, name):
self.name = name
def sayHi(self):
print 'Hello, my name is', self.name
def sayHiTo(self, other):
print 'Hello', other.name, ' my name is', self.name
p1 = Person('Swaroop')
p2 = Person('codeninja')
p1.sayHiTo(p2)
p2.sayHiTo(p1)
Actually no. Your second example is not correct.
The 'self' keyword is a special reference that is passed to instance methods of a class. It represents the actual instance of the class at that scope. When you make a class it is just a general definition. Then you create instances of that class. Each instance is unique and thus the methods have to be able to work on that instance. You have no way of knowing them until they are made so 'self' passes them in for you.
For instance, if you created two instances of your person class:
p1 = Person("john")
p2 = Person("sam")
self.name value is different for each of those. And when you call sayHi() on each instance:
p1.sayHi()
> Hello, my name is john
p2. sayHi()
> Hello, my name is sam
You would not use the self keyword for unbound functions. That is, just general functions like what you have written as your second example. You would instead have to write it like this;
def sayHi(name):
print 'Hello, my name is', name
p = Person('Swaroop')
p.sayHi()
> sayHi("john")
But that would basically just pass a name string to a Person class and call its method. The idea here is that you create unique instances of Person with their own properties.
The purpose is to store the reference to the name so you can reference it in another method of the class e.g. def sayHi (self)
You can't compare a function in a class to just a function. Sure you can pass in name, but the idea of using a class is that you are encapsulating data. Having vars linked to self means you can pass around an object, and that object can always have access to its 'member variables'. Some other class can use an instance of Person and not need to know that persons name in order to say hi.