Python Forum
problem with class method - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: problem with class method (/thread-16014.html)



problem with class method - AmirAB - Feb-10-2019

Hi experts. I am new to Python but understand programming and have a fair idea about it. I need your help for following.

I am trying to execute the following code but getting an error. Both error and code provided below.

class Circle():
    pie=3.14
    def __init__(self,radius=1):
        self.radius=radius
        self.area=pie*radius*radius
        
        
    def Circum(self):
        return(2*self.pie*self.radius)

mycircle=Circle()
mycircle.Circum()     # I get error here when calling this function
Error:
TypeError: Circum() takes 0 positional arguments but 1 was given


RE: problem with class method - buran - Feb-10-2019

hm, that is strange. The actual error I get is
Error:
Traceback (most recent call last): File "/home/boyan/sandbox/classes/enemy.py", line 11, in <module> mycircle=Circle() File "/home/boyan/sandbox/classes/enemy.py", line 5, in __init__ self.area=pie*radius*radius NameError: name 'pie' is not defined
you can fix that by changing it to self.pie
then the code will run, but in order to see the output of Circum, you need to add print()
e.g. print(mycircle.Circum())


RE: problem with class method - snippsat - Feb-10-2019

As your radius is a default argument,then so can pie be.
It can also be be a class attribute with self.pie as @buran suggests.
class Circle:
    def __init__(self, radius=1, pie=3.14):
        self.radius = radius
        self.pie = pie
        self.area = self.pie * self.radius * self.radius

    def circum(self):
        return(2 * self.pie * self.rad
Use:
>>> mycircle = Circle()
>>> mycircle.circum()
6.28

>>> # Can change radius,pie is the same as it always has been 
>>> mycircle = Circle(2)
>>> mycircle.circum()
12.56
Also look at PEP-8,for small changes that i made.


RE: problem with class method - AmirAB - Feb-13-2019

(Feb-10-2019, 09:39 PM)snippsat Wrote: As your radius is a default argument,then so can pie be. It can also be be a class attribute with self.pie as @buran suggests.
class Circle: def __init__(self, radius=1, pie=3.14): self.radius = radius self.pie = pie self.area = self.pie * self.radius * self.radius def circum(self): return(2 * self.pie * self.rad
Use:
>>> mycircle = Circle() >>> mycircle.circum() 6.28 >>> # Can change radius,pie is the same as it always has been >>> mycircle = Circle(2) >>> mycircle.circum() 12.56
Also look at PEP-8,for small changes that i made.

Great ... :)
Thanks a lot Bros...it feels awesome getting so much help..
Bundle of thanks both of you @buran, @snippsat