Programming in python : Classes

Create a class as follows,

>>> class abc():
… a = 1
… b = 2

create x as an instance of the class abc,

>>> x = abc()
>>> x

>>> x.b
2
Create another class with a function definition,

>>> class abc():
… a = 3
… b = 4
… def fun():
… print ‘hello’

>>> x = abc()
>>> x.a
3
>>> x.b
4
>>> x.fun()
Traceback (most recent call last):
File “”, line 1, in
TypeError: fun() takes no arguments (1 given)

We cannot call the function in class abc, as an attribute of x. x has no such an attribute. But the address of x is already given by the interpreter as a parameter to that function. Usually we give an extra parameter ‘self’, have no special meaning.

>>> class abc():
… a = 1
… b = 2
… def fun(self):
… p = 5
… q = 6
… print ‘hello’

>>> x = abc()
>>> x.a
>>> 1
>>> x.p
>>> x.fun()
The above statement causes an error. Because x has no attribute p. ‘x.fun()’ cannot print hello, so little changes are needed to our code and is shown below.

>>> class abc():
… x = 1
… y = 2
… def fun(self):
… self.p = 3
… self.q = 4
… print ‘Hello’

>>> m = abc()
>>> m.p
Traceback (most recent call last):
File “”, line 1, in
AttributeError: abc instance has no attribute ‘p’

Here the interpreter says that the abc instance has no attribute ‘p’.’p’ is an attribute of the function ‘fun’. So create an instance of abc and pass the address of m to ‘self’.

>>> m = abc()
>>> m .fun()
Hello

Advertisement

Author: Abhilash

I'm Abhilash, a web developer who specializes in Ruby development. With years of experience working with various frameworks like Rails, Angular, Sinatra, Laravel, NodeJS, React and more, I am passionate about building robust and scalable web applications. Since 2010, I have been honing my skills and expertise in the Ruby on Rails platform. This blog is dedicated to sharing my knowledge and experience on topics related to Ruby, Ruby on Rails, and other subjects that I have worked with throughout my career. Join me on this journey to explore the exciting world of web development!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: